On this page
  1. <stdio.h> & File I/O
  2. Contents
  3. Safe Formatting & Line Input (snprintf & fgets)
  4. Binary & Buffered File I/O

<stdio.h> & File I/O

Prev: stdlib | Up: stdlib | Next: stdlib.h & string.h
Rel: Error Handling & goto cleanup
Ref: cppreference — C File I/O
Tags: #public #prog #c #stdlib #io


Contents


Safe Formatting & Line Input (snprintf & fgets)

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

int read_first_line(const char *path, char *out, size_t out_size) {
    FILE *fp = fopen(path, "r");
    if (!fp) {
        fprintf(stderr, "open %s failed: %s\n", path, strerror(errno));
        return -1;
    }
    int rc = fgets(out, (int)out_size, fp) ? 0 : -1;
    fclose(fp);
    return rc;
}

Binary & Buffered File I/O

For raw byte streams, open with "rb" / "wb" and check the item count returned by fread(ptr, size, count, fp) / fwrite(...), plus ferror(fp) and feof(fp).

Linked from

Related notes