C Cheatsheet

File I/O

Use this C reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Opening and Closing Files

#include <stdio.h>

FILE *fp = fopen("file.txt", "r");   // returns NULL on failure
if (!fp) {
    perror("fopen");    // prints "fopen: No such file or directory"
    return -1;
}

// ... use fp ...

fclose(fp);             // returns EOF on error

File Open Modes

ModeMeaning
"r"Open text file for reading
"w"Create/truncate text file for writing
"a"Open text file for appending
"r+"Open text file for reading and writing
"w+"Create/truncate text file for reading and writing
"a+"Open text file for reading and appending
"rb"Binary reading
"wb"Binary writing
"ab"Binary appending
"rb+" / "r+b"Binary reading and writing
"wb+" / "w+b"Binary reading and writing (truncate)

On POSIX systems, text and binary modes are identical. On Windows, \n\r\n translation happens in text mode.

Standard Streams

stdin   // standard input  (FILE *)
stdout  // standard output (FILE *)
stderr  // standard error  (FILE *)

// stderr is unbuffered; stdout may be line-buffered or fully buffered
fprintf(stderr, "Error: %s\n", msg);

Text Reading

// Read one character
int c = fgetc(fp);            // returns EOF on end or error
int c2 = getc(fp);            // may be macro; same semantics

// Read one line
char buf[256];
if (fgets(buf, sizeof buf, fp)) {  // returns NULL on EOF/error
    // buf includes '\n'; check and strip if needed
    buf[strcspn(buf, "\n")] = '\0';
}

// Read until EOF
while ((c = fgetc(fp)) != EOF) { putchar(c); }
while (fgets(buf, sizeof buf, fp)) { printf("%s", buf); }

// Formatted read
int n; float f;
fscanf(fp, "%d %f", &n, &f);   // returns number of items matched

Text Writing

// Write one character
fputc('A', fp);
putc('\n', fp);

// Write a string
fputs("hello\n", fp);          // no automatic newline added

// Formatted write
fprintf(fp, "x = %d, y = %.2f\n", x, y);

// Write to stdout shorthand
printf("...");                 // same as fprintf(stdout, "...")
puts("line");                  // like fputs("line\n", stdout)
putchar('c');                  // like fputc('c', stdout)

Binary Reading and Writing

// fread(buf, element_size, count, fp) → elements read
size_t n = fread(buf, sizeof(int), 10, fp);  // read up to 10 ints

// fwrite(buf, element_size, count, fp) → elements written
int arr[] = {1, 2, 3, 4, 5};
fwrite(arr, sizeof(int), 5, fp);

// Check for errors after fread
if (n < 10) {
    if (feof(fp))   fprintf(stderr, "End of file reached\n");
    if (ferror(fp)) perror("fread");
}

// Read/write a single struct
Student s = {.id=1, .score=95.0};
fwrite(&s, sizeof(Student), 1, fp);
fread(&s,  sizeof(Student), 1, fp);

File Positioning

// ftell — current position in bytes from start
long pos = ftell(fp);

// fseek — move to position
fseek(fp, 0L, SEEK_SET);    // beginning of file
fseek(fp, 0L, SEEK_END);    // end of file
fseek(fp, -4L, SEEK_CUR);   // 4 bytes before current position
fseek(fp, pos, SEEK_SET);   // restore saved position

// rewind — go back to start, also clears error indicator
rewind(fp);

// Large files (POSIX)
off_t pos2 = ftello(fp);
fseeko(fp, pos2, SEEK_SET);

// fgetpos / fsetpos — portable opaque position
fpos_t fpos;
fgetpos(fp, &fpos);
fsetpos(fp, &fpos);
ConstantMeaning
SEEK_SETFrom beginning of file
SEEK_CURFrom current position
SEEK_ENDFrom end of file

Error Checking

// Test for end-of-file
int c = fgetc(fp);
if (c == EOF) {
    if (feof(fp))   printf("end of file\n");
    if (ferror(fp)) perror("I/O error");
}

feof(fp)       // nonzero if EOF reached
ferror(fp)     // nonzero if error occurred
clearerr(fp)   // clear EOF and error flags

// errno is set by most I/O failures
#include <errno.h>
if (!fopen("x", "r")) printf("errno: %d (%s)\n", errno, strerror(errno));
perror("fopen");   // prints "fopen: <error string>"

Flushing and Buffering

fflush(fp);         // flush output buffer to OS
fflush(stdout);     // flush stdout (useful before scanf or after printf)
fflush(NULL);       // flush all open output streams

// Set buffering mode
setvbuf(fp, NULL, _IOFBF, 4096);  // full buffering, 4 KB buffer
setvbuf(fp, NULL, _IOLBF, 0);     // line buffering
setvbuf(fp, NULL, _IONBF, 0);     // no buffering

// Must call before any I/O on the stream
setbuf(fp, buf);    // buf is BUFSIZ bytes, or NULL for no buffering

String Streams

// snprintf — format into a buffer
char buf[128];
snprintf(buf, sizeof buf, "x=%d, name=%s", 42, "Alice");

// sscanf — parse from a buffer
int n; float f; char name[32];
sscanf(buf, "%d %f %31s", &n, &f, name);

Temporary Files

// Create a temporary file — automatically deleted on close
FILE *tmp = tmpfile();   // returns NULL on failure

// Get a unique temporary filename (deprecated — use tmpfile() instead)
char name[L_tmpnam];
tmpnam(name);    // security concern: TOCTOU race; prefer tmpfile()

// POSIX alternatives
int fd = mkstemp(template);  // "tmpXXXXXX" → fills in X's

File System Operations (<stdio.h>, <stdlib.h>)

// Rename / move
rename("old.txt", "new.txt");   // returns 0 on success

// Delete
remove("file.txt");             // returns 0 on success

// Check existence (POSIX <unistd.h>)
#include <unistd.h>
if (access("file.txt", F_OK) == 0) printf("exists\n");
if (access("file.txt", R_OK) == 0) printf("readable\n");
if (access("file.txt", W_OK) == 0) printf("writable\n");

Complete Read-File Example

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

char *read_file(const char *path, long *out_len) {
    FILE *fp = fopen(path, "rb");
    if (!fp) return NULL;

    fseek(fp, 0, SEEK_END);
    long len = ftell(fp);
    rewind(fp);

    char *buf = malloc(len + 1);
    if (!buf) { fclose(fp); return NULL; }

    size_t read = fread(buf, 1, len, fp);
    fclose(fp);
    buf[read] = '\0';
    if (out_len) *out_len = (long)read;
    return buf;   // caller must free
}

Line-by-Line Processing

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

FILE *fp = fopen("data.txt", "r");
char line[1024];
int lineno = 0;

while (fgets(line, sizeof line, fp)) {
    lineno++;
    line[strcspn(line, "\n")] = '\0';   // strip trailing newline
    printf("%3d: %s\n", lineno, line);
}

fclose(fp);