Site Tools


h-stdio

Table of Contents

<stdio.h>

<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.

Example

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;
}

Common functions

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 closing
  • rewind(file): seek to beginning
  • fseek(file, offset, whence): seek to position (SEEK_SET, SEEK_CUR, SEEK_END)
  • ftell(file): current file position
  • remove(path): delete file
  • rename(old, new): rename file

Formatted output (to stdout, file, or buffer):

  • printf(fmt, ...): formatted output to stdout
  • fprintf(file, fmt, ...): formatted output to file
  • sprintf(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 versions

Formatted input (from stdin or file):

  • scanf(fmt, ...): formatted input from stdin
  • fscanf(file, fmt, ...): formatted input from file
  • sscanf(str, fmt, ...): formatted input from string
  • vscanf(fmt, args), vfscanf(f, fmt, args), vsscanf(s, fmt, args): variadic versions

Text I/O (line-oriented):

  • fgets(buf, size, file): read up to size-1 characters or newline
  • fputs(str, file): write string (without null terminator)
  • getchar(): read character from stdin
  • putchar(c): write character to stdout
  • fgetc(file): read character from file
  • fputc(c, file): write character to file

Binary I/O:

  • fread(buf, size, count, file): read count objects of size bytes
  • fwrite(data, size, count, file): write count objects of size bytes

Error handling:

  • perror(msg): print system error message to stderr
  • ferror(file): check error flag
  • clearerr(file): clear error flag
  • eof(file): check end-of-file flag
  • fseek(file, offset, whence): seek to position
  • rewind(file): seek to start of file
  • perror(msg): print error message with errno
h-stdio.md · Last modified: by 127.0.0.1