File I/O
Open, read, write, and close files using the stdio FILE API.
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
Pointer Basics
Declare pointers, dereference, and walk an array with pointer arithmetic.
Memory Management
Allocate, resize, and free heap memory with malloc, realloc, and free.
String Operations
Use string.h helpers for length, copy, concat, compare, and tokenize.
Structs
Group related fields with typedef and pass by pointer for mutation.
Function Pointers
Store function addresses for callbacks and dispatch tables.
Preprocessor Macros
Define object-like and function-like macros with conditional compilation.