Lesson 30 / 36

Opening & Closing Files

fopen, modes, and always checking for failure.

FILE* is your handle

fopen(path, mode) returns a FILE * used for all further operations on that file, or NULL if it couldn't be opened. Always check for NULL before using it.

Modes

"r" read, "w" write (truncates or creates), "a" append, "r+" read+write. Append a b for binary mode.

FILE *fp = fopen("notes.txt", "w");
if (fp == NULL) {
    perror("fopen failed");
    return 1;
}

fprintf(fp, "Hello, file!\n");
fclose(fp);

Always close

fclose(fp) flushes buffered writes to disk and releases the file handle. Forgetting it can lose data still sitting in the buffer.