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:

  • Purpose: Reads a single character from a file.

  • Syntax: int getc(FILE *stream);

Examples

Reading from a file:

#include <stdio.h>
int main() {
    char ch = '\0';
    FILE *fp;
    if ((fp = fopen("test","r")) != NULL) {
        while ((ch = getc(fp)) != EOF) {
            printf("%c",ch);
        }
        fclose(fp);
    }
    return 0;
}

Reading from stdin (i.e., keyboard):

Alternative methods:

With spaces captured:

ungetc()Function:

  • Purpose: Pushes a character back into the stream.

  • Syntax: int ungetc(int char, FILE *stream);

Example:

Character Functions for Output

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:

  • 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:

  • 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():

fscanf()Function:

  • Purpose: Reads formatted input from a file.

  • Syntax: int fscanf(FILE *fp, const char *format, ...);

Example:

Formatting Functions

sprintf()Function:

  • Purpose: Writes formatted output to a string.

  • Syntax: int sprintf(char *str, const char *format, ...);

Example:

Last updated