Streams

Overview

Streams are represented in C using opaque type FILE *. By default, stdin is open for input. By default, stdout and stderr are open for output. Files are typically managed with

FILE* fopen(const char *restrict filename, const char *restrict mode);
int fclose(FILE *stream);

Open file descriptors can be examined or modified using fcntl():

int fcntl(int fd, int op, ... /* arg */ );

All stream functions besides fopen and fclose are race-free meaning a properly initialized FILE* can be used race-free by several threads. To avoid garbled output lines, calls to printing-related functions should always print an entire line. That is, concurrent write operations should print entire lines at once.

Buffering

Output to streams is usually buffered, meaning the IO system delays the physical write to a stream. To flush a stream is to force the write. The following C function is used to perform a flush:

int fflush(FILE *stream);

The most common form of IO buffering for text files is line buffering. In this mode, output is only physically written if the end of a text line is encountered.

Reading

Raw

The most commonly used function for reading raw data is fread. This is likely a wrapper around the read syscall.

size_t fread(void *restrict ptr,
             size_t size, size_t nmemb,
             FILE *restrict stream);

Unformatted Text

The most commonly used functions for reading unformatted text are fgetc and fgets. The latter reads from a stream until a newline is encountered or the specified limit is reached.

int fgetc(FILE *stream);
char *fgets(char *restrict s, int n, FILE *restrict stream);

Formatted Text

The most commonly used function for reading formatted text is fscanf. The syntax for the format placeholder is %[*][width][length]specifier.

int fscanf(FILE *restrict stream, const char *restrict format, ...);

Writing

Raw

The most commonly used function for writing raw data is fwrite. This is likely a wrapper around the write syscall.

size_t fwrite(const void *restrict ptr,
              size_t size, size_t nmemb,
              FILE *restrict stream);

Unformatted Text

The most commonly used functions for writing unformatted text are fputc and fputs.

int fputc(int c, FILE *stream);
int fputs(const char *restrict s, FILE *restrict stream);

Formatted Text

The most commonly used function for writing formatted text is fprintf. The syntax for the format placeholder is %[flags][width][.precision][length]specifier.

int fprintf(FILE *restrict stream, const char *restrict format, ...);
Powered by Forestry.md