1 minute read

Here lists several methods for input/output in C.

Methods and Examples

getline

#include <stdio.h>
ssize_t getline(char **restrict lineptr, size_t *restrict n,
                FILE *restrict stream);
  • getline can be used for getting a line of input from a stream. It regards '\n' as the separator and stops with EOF. The string will include both null-terminated and the newline character. It will NOT regard space character and tab as the separator. For reading space separated input, check fscanf.
  • lineptr can be set as NULL or assigned with malloc. getline will malloc if lineptr is NULL or directly use/resize according to input length respectively. The address of the buffer pointer should be fed into getline because it may assign a new value to the pointer. The actual string size will be stored in n.
  • Remember to free the buffer afterwards.

  • More details about getline: getline(3) - Linux manual page (man7.org)

fgets

#include <stdio.h>
char *fgets(char *restrict s, int n, FILE *restrict stream);
  • fgets can be used for getting a line of input from a stream with maximum length limitation on the string. It regards '\n' as the separator and stops with EOF or maximum length limitation. The string will include both null-terminated and the newline character. Similar to getline, it does NOT regard space and tab as separator.

  • More details about fgets: fgets(3p) - Linux manual page (man7.org)

fscanf

#include <stdio.h>
int fscanf(FILE *restrict stream, const char *restrict format, ...);
  • fscanf can be used for getting inputs from a stream with space, tab, newline as separators.
  • For string format, regular expression can be used.
  • When reading inputs from stdin, if several fscanf functions are sequentially placed, these functions will read until the input buffer becomes empty with no blocking.

  • More details about fscanf: fscanf(3p) - Linux manual page (man7.org)

Reference

Updated: