8.3 Character, String, and Line I/O
C also gives you smaller I/O tools for individual characters and whole strings. These work with the console streams stdin and stdout, or with file streams opened by fopen().
| Function | Stream | What it does | Important detail |
|---|---|---|---|
getchar() | stdin | Reads one character | Returns int, so it can return EOF |
putchar(ch) | stdout | Writes one character | Sends exactly one character |
fgetc(fp) | file stream | Reads one character from a file | Returns int for EOF |
fputc(ch, fp) | file stream | Writes one character to a file | Useful for character filters |
puts(text) | stdout | Writes a string | Adds a newline |
fputs(text, fp) | file stream | Writes a string | Does not add a newline |
fgets(buf, size, stream) | any input stream | Reads at most size - 1 characters | Keeps the buffer inside its limit |
gets(buf) | stdin | Old unsafe line input | Do not use it; it has no size limit |
Single-character console I/O often looks like this:
c
int ch;
while ((ch = getchar()) != EOF) {
putchar(ch);
}The same pattern can transform a file one character at a time:
c
FILE *in = fopen("raw.txt", "r");
FILE *out = fopen("clean.txt", "w");
int ch;
while ((ch = fgetc(in)) != EOF) {
if (ch == '\t') {
fputc(' ', out);
} else {
fputc(ch, out);
}
}
fclose(out);
fclose(in);For strings and lines, prefer fgets() because it receives the buffer size:
c
char line[80];
while (fgets(line, sizeof(line), stdin) != NULL) {
fputs(line, stdout);
}You may see gets(buffer) in old material, but it cannot know how large buffer is. It can write past the end of the array, so modern C removed it. Use fgets() instead.
Loading interactive lab...
Loading concept check...
Loading practice...