<stdio.h> provides buffered file and console I/O: printf, scanf, fopen, fclose, and stream operations. Use snprintf instead of sprintf to avoid buffer overflows; always check return values.
Compile with -lm if using math functions; I/O functions link with the C library automatically.
This example opens a file, writes formatted data, seeks, and reads it back.
// compile: gcc -o studioexample studioexample.c // run: ./studioexample // description: write to file, seek to start, read back line by line #include <stdio.h> int main() { FILE* f = fopen("/tmp/stdio.txt", "w+"); if (!f) { perror("fopen"); return 1; } fprintf(f, "line 1\n"); fprintf(f, "line 2\n"); fprintf(f, "line 3\n"); rewind(f); char buf[64]; while (fgets(buf, sizeof(buf), f)) printf("read: %s", buf); fclose(f); return 0; }
File operations:
fopen(path, mode): open file (“r”, “w”, “a”, “r+”, “rb”, “wb”, etc.)fclose(file): close file (flushes and releases)fflush(file): flush output buffer without closingrewind(file): seek to beginningfseek(file, offset, whence): seek to position (SEEK_SET, SEEK_CUR, SEEK_END)ftell(file): current file positionremove(path): delete filerename(old, new): rename fileFormatted output (to stdout, file, or buffer):
printf(fmt, ...): formatted output to stdoutfprintf(file, fmt, ...): formatted output to filesprintf(buf, fmt, ...): formatted output to buffer (unsafe, use snprintf)snprintf(buf, size, fmt, ...): formatted output to buffer (safe, no overflow)vprintf(fmt, args), vfprintf(f, fmt, args), vsnprintf(buf, size, fmt, args): variadic versionsFormatted input (from stdin or file):
scanf(fmt, ...): formatted input from stdinfscanf(file, fmt, ...): formatted input from filesscanf(str, fmt, ...): formatted input from stringvscanf(fmt, args), vfscanf(f, fmt, args), vsscanf(s, fmt, args): variadic versionsText I/O (line-oriented):
fgets(buf, size, file): read up to size-1 characters or newlinefputs(str, file): write string (without null terminator)getchar(): read character from stdinputchar(c): write character to stdoutfgetc(file): read character from filefputc(c, file): write character to fileBinary I/O:
fread(buf, size, count, file): read count objects of size bytesfwrite(data, size, count, file): write count objects of size bytesError handling:
perror(msg): print system error message to stderrferror(file): check error flagclearerr(file): clear error flageof(file): check end-of-file flagfseek(file, offset, whence): seek to positionrewind(file): seek to start of fileperror(msg): print error message with errno