6

I would like to have a FILE* type to use fprintf. I need to use fdopen to get a FILE* instead of open that returns an int. But can we do the same with fdopen and open? (I never used fdopen)

I would like to do a fdopen that does the same as :

open("my_file", 0_CREAT | O_RDWR | O_TRUNC, 0644);
tshepang
  • 12,111
  • 21
  • 91
  • 136
Elfayer
  • 4,411
  • 9
  • 46
  • 76

3 Answers3

9

fdopen()use file descriptor to file pointer:

The fdopen() function associates a stream with a file descriptor. File descriptors are obtained from open(), dup(), creat(), or pipe(), which open files but do not return pointers to a FILE structure stream. Streams are necessary input for almost all of the stdio library routines.

FILE* fp = fdopen(fd, "w");

this example code may help you more as you want to use fprintf():

int main(){
 int fd;
 FILE *fp;
 fd = open("my_file",O_WRONLY | O_CREAT | O_TRUNC);
  if(fd<0){
    printf("open call fail");
    return -1;
 }
 fp=fdopen(fd,"w");
 fprintf(fp,"we got file pointer fp bu using File descriptor fd");
 fclose(fp);
 return 0;
}

Notice:

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • 3
    You should *not* close the file descriptor after having used `fdopen` on it and then `fclose`. The `fd` is *not* dup'ed and calling `fclose` will close it. – Jite Feb 27 '13 at 11:26
  • Quoting man page: `The file descriptor is not dup'ed, and will be closed when the stream created by fdopen() is closed.` Also see http://stackoverflow.com/questions/8417123/mixing-fdopen-and-open-bad-file-descriptor – Jite Feb 27 '13 at 11:30
  • That doesn't write anything in the file. – Elfayer Feb 27 '13 at 11:37
  • @Elfayer It should work, Try again also here is one more [example](http://publib.boulder.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Frtref%2Ffdopen.htm) – Grijesh Chauhan Feb 27 '13 at 11:42
9

fdopen takes a file descriptor that could be previously returned by open, so that is not a problem.

Just open your file getting the descriptor, and then fdopen that descriptor.

fdopen simply creates a userspace-buffered stream, taking any kind of descriptor that supports the read and write operations.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
  • 3
    Don't forget to that the modes to `fdopen` must be compatible with the file descriptor ones. – Jite Feb 27 '13 at 11:18
1

If you don't have previously acquired a file-descriptor for your file, rather use fopen.

FILE* file = fopen("pathtoyourfile", "w+");

Consider, that fopen is using the stand-library-calls and not the system-calls (open). So you don't have that many options (like specifying the access-control-values).

See the man-page.

bash.d
  • 13,029
  • 3
  • 29
  • 42