I/O
This guide discusses the C functions used for reading and writing characters and strings, with examples of their usage.
Character Functions for Input
getc()
Function:
getc()
Function:Purpose: Reads a single character from a file.
Syntax:
int getc(FILE *stream);
Examples
Reading from a file:
Reading from stdin
(i.e., keyboard):
stdin
(i.e., keyboard):Alternative methods:
With spaces captured:
ungetc()
Function:
ungetc()
Function:Purpose: Pushes a character back into the stream.
Syntax:
int ungetc(int char, FILE *stream);
Example:
Character Functions for Output
putc()
Function:
putc()
Function:Purpose: Writes a single character to a file or stdout.
Syntax:
int putc(int char, FILE *fp);
Usage:
putc('\n', stdout);
Example
Redirecting input to a file:
Use the program like:
./main < infile
fputc()
Function:
fputc()
Function:Purpose: Writes a character to the specified stream.
Syntax:
int fputc(int character, FILE *stream);
Example
Writing characters a-z to a file:
String Functions for Input
getline()
Function:
getline()
Function:Purpose: Reads a line from the specified stream.
Syntax:
ssize_t getline(char **buffer, size_t *size, FILE *stream);
Example
Reading a line with getline()
:
getline()
:fscanf()
Function:
fscanf()
Function:Purpose: Reads formatted input from a file.
Syntax:
int fscanf(FILE *fp, const char *format, ...);
Example:
Formatting Functions
sprintf()
Function:
sprintf()
Function:Purpose: Writes formatted output to a string.
Syntax:
int sprintf(char *str, const char *format, ...);
Example:
Last updated