From C To Pascal, Files

Frank Heckenbach frank at g-n-u.de
Tue Sep 5 22:52:28 CEST 2000


Eike Lange wrote:

> Its for the PostgreSQL-Unit.
> 
> In C, I have a function:
> void printSomethingToFile(File* file);
> 
> for which I want to write a wrapper.
> What I did was:
> 
> ----------------- snip --------------
> In C:
> 
> void _p_printSomethingToFile(int file_descriptor)
> {
>   FILE *myfile;
>   myfile = fdopen(file_descriptor, "w");
>   /* if (errno != 0) printf("errno is %d\n"errno); */
>   printSomethingToFile(myfile);
>   /* fflush(myfile); */
> }
> 
> Pascal (Unit-Part):
> 
> Procedure CprintSomethingToFile(int file_descriptor);
> asmname '_p_printSomethingToFile';
> 
> Procedure PrintSomethingToFile(aFile : Text);
> Var
>   fd : Integer;
> Begin
>   fd := FileHandle(aFile);
>   CprintSomethingToFile(fd)
> End;
> 
> Pascal (Program)
> 
> Var
>   f : Text;
> Begin
>   ...
>   Assign(f, 'filename.out');
>   Rewrite(f);
>   PrintSomethingToFile(f);
>   Close(f);
>   ...
> End.
> ----------------- snip --------------
> 
> Sometimes this works (especially, if I
> write a line of text _before_ I use
> PrintSomethingToFile) and sometimes it fails because
> errno is set to a value <> 0 after calling fdopen.

I'm no C expert, but I think you should check the function result
first, and only if it indicates an error (< 0 for integers, NULL for
pointers), errno is meaningful. (I'm not trying to "define away" a
problem, but I don't think there's actually a problem...)

> If I use fflush(myfile) after (in C) 
> printSomethingToFile(myfile) it seems to work.
> The text is written propely, but errno is <>0 !

Yes, you need to fflush to file, otherwise the C code doesn't know
that it should flush the data.

Actually, there may be a problem here: You (fd)open a C file and
never close it. I don't know if the libc (on any system) likes this
-- perhaps it will slow down or blow up when doing this too often...

OTOH, you can't just fclose the file because it would also close the
fd and confuse the Pascal RTS. So, unless you find a better
solution, you might have to do something as awkward as creating a
temporary fd using dup. The following seems to work:

  myfile = fdopen(dup (file_descriptor), "w");
  if (!myfile) printf("errno is %d\n",errno);
  printSomethingToFile(myfile);
  fclose(myfile);

Anyway, if a function that outputs to a string rather than a file is
available in the library, I'd suggeest to use (only) this instead.
But if it isn't, you might have to do it like this.

Frank

-- 
Frank Heckenbach, frank at g-n-u.de, http://fjf.gnu.de/
GPC To-Do list, latest features, fixed bugs:
http://agnes.dida.physik.uni-essen.de/~gnu-pascal/todo.html




More information about the Gpc mailing list