Skip to content
C

File I/O

Open, read, write, and close files using the stdio FILE API.

#file-io#stdio

Code

c
#include <stdio.h>
#include <string.h>

int main(void) {
    // Write text
    FILE *out = fopen("data.txt", "w");
    if (!out) { perror("fopen"); return 1; }
    fprintf(out, "line %d\n", 1);
    fputs("hello\n", out);
    fclose(out);

    // Read text line by line
    FILE *in = fopen("data.txt", "r");
    if (!in) { perror("fopen"); return 1; }

    char buf[256];
    while (fgets(buf, sizeof(buf), in)) {
        // strip trailing newline
        buf[strcspn(buf, "\n")] = '\0';
        printf("> %s\n", buf);
    }
    fclose(in);

    // Binary I/O
    int nums[] = {1, 2, 3, 4, 5};
    FILE *b = fopen("nums.bin", "wb");
    fwrite(nums, sizeof(int), 5, b);
    fclose(b);
    return 0;
}