Lesson 10 of 12

File I/O

Learn to open, read, write and close files with C's FILE streams, and how to check for along the way.

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    /* Modes: "r" read, "w" truncate+write, "a" append, "r+" read/write,
       add "b" for binary ("rb", "wb") */
    FILE *out = fopen("notes.txt", "w");
    if (!out) { perror("fopen"); return 1; }

    fprintf(out, "line %d\n", 1);
    fputs("line 2\n", out);
    fclose(out);                      /* flushes; skipping this can lose data */

    FILE *in = fopen("notes.txt", "r");
    if (!in) { perror("fopen"); return 1; }

    char line[256];
    while (fgets(line, sizeof line, in) != NULL) {
        line[strcspn(line, "\n")] = '\0';    /* strip the trailing newline */
        printf("[%s]\n", line);
    }
    if (ferror(in)) fprintf(stderr, "read error\n");
    fclose(in);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Read an entire file into a heap buffer */
char *read_all(const char *path, long *out_size) {
    FILE *f = fopen(path, "rb");
    if (!f) return NULL;

    fseek(f, 0, SEEK_END);
    long size = ftell(f);              /* current position = file length */
    rewind(f);                         /* back to the start */

    char *buffer = malloc((size_t)size + 1);
    if (!buffer) { fclose(f); return NULL; }

    size_t read = fread(buffer, 1, (size_t)size, f);
    buffer[read] = '\0';
    fclose(f);

    if (out_size) *out_size = (long)read;
    return buffer;                     /* caller must free */
}

/* Binary records: fwrite/fread move raw bytes */
typedef struct { int id; char name[32]; double score; } Record;

int save_records(const char *path, const Record *recs, size_t n) {
    FILE *f = fopen(path, "wb");
    if (!f) return -1;
    size_t written = fwrite(recs, sizeof *recs, n, f);
    fclose(f);
    return written == n ? 0 : -1;
}

int main(void) {
    Record recs[2] = { {1, "Ada", 99.5}, {2, "Grace", 98.0} };
    save_records("data.bin", recs, 2);

    long size = 0;
    char *text = read_all("notes.txt", &size);
    if (text) { printf("%ld bytes\n", size); free(text); }
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* A tiny CSV reader — parsing with strtok */
void parse_csv(const char *path) {
    FILE *f = fopen(path, "r");
    if (!f) { perror(path); return; }

    char line[512];
    int lineno = 0;

    while (fgets(line, sizeof line, f)) {
        lineno++;
        if (lineno == 1) continue;                 /* skip the header */
        line[strcspn(line, "\r\n")] = '\0';

        char *id    = strtok(line, ",");
        char *name  = strtok(NULL, ",");
        char *score = strtok(NULL, ",");
        if (!id || !name || !score) {
            fprintf(stderr, "malformed line %d\n", lineno);
            continue;
        }
        printf("%s -> %s (%.1f)\n", id, name, atof(score));
    }
    fclose(f);
}

/* Command line arguments and standard streams */
int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "usage: %s <file.csv>\n", argv[0]);   /* errors go to stderr */
        return 1;
    }
    parse_csv(argv[1]);
    return 0;
}
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.