Search notes:

libc: open / fopen

Interestingly, the man page for open is in the 2nd section while the man page for fopen is in the 3rd section.

open

Note: open() needs the include file <fcntl.h>, but the corresponding close() needs <unistd.h>.
#include <fcntl.h>

#include <unistd.h> // close()
#include <stdio.h>  // printf()
#include <stdlib.h> // exit()
#include <string.h> // strlen()

int main() {

    int flags =
        O_WRONLY| // O_RDONLY, O_RDWR
        O_CREAT | // O_EXCL, O_TMPFILE, O_NONBLOCK, O_NOCTTY, O_TRUNC
        0       ; // O_APPEND, O_NONBLOCK, O_NOATIME

    mode_t mode =
        S_IRUSR | // user read
        S_IWUSR ; // user write

    int file_descriptor = open("out-file", flags, mode);
    if (file_descriptor < 0) {
      printf("Could not open file\n");
      exit(1);
    }

    char*  text = "foo\nbar\nbaz\n";
    size_t size = strlen(text);

 //
 // GNU's manual says:
 //     The return value is the number of bytes actually written. This may be
 //     size, but can always be smaller. Your program should always call write
 //     in a loop, iterating until all the data is written.
    int written = write(file_descriptor, text, size);

    close(file_descriptor);
}
Github repository about-libc, path: /functions/open/open.c

fopen

fopen returns a pointer to a FILE struct.
#include <stdio.h>

#include <stdlib.h>  // exit()

int main() {

   FILE* f = fopen("a.file", "w");

   if (!f) {
     printf("Could not open file\n");
     exit(1);
   }

   fprintf(f, "foo\nbar\nbaz\n");

   fclose(f);
}
Github repository about-libc, path: /functions/open/fopen.c

See also

The Standard C Library

Index