← The C Language Lesson 35 of 77 · 10 XP

Creating files

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

In C you work with files through a FILE * pointer from <stdio.h>:

FILE *f = fopen("notes.txt", "w");    // open (create) for writing
if (f == NULL) {
    perror("fopen");                  // prints the reason: No such file or directory…
    return 1;
}
...
fclose(f);                            // always close it

fopen modes:

mode what it does
"r" reading; the file must exist
"w" writing; creates the file or erases an existing one
"a" appending to the end; creates the file if there isn't one
"r+", "w+", "a+" reading and writing
"wx" create a new file; an error if it already exists (C11)

Always check the result of fopen: the file may not exist, you may lack permissions, the disk may run out of space. NULL signals an error.

fclose flushes the buffer to disk. If you don't close the file, the last data may never get written.

Here the program works with its own small file system in the browser: the files live while the program is running.

Task. Try to open the file config.txt for reading. It doesn't exist, so print not found. Then create it in "w" mode, close it, open it for reading again and print created.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.