Skip to content
C

File I/O

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

By EZ4Code Team
file-iostdio

Code

#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;
}

Explanation

fopen opens a file in modes such as r, w, and wb, returning a FILE pointer that you must close. fprintf and fputs write formatted or raw text while fgets reads one line safely into a fixed-size buffer. fread and fwrite handle binary records in bulk, which is faster and more compact than parsing text.

More C Snippets