<stdio.h> gives three FILE * streams already open in a hosted program: stdin, stdout, stderr.
stderr so they survive stdout redirection.fopen is the same API; we skip file-lifetime details (Wave B).Mental model: formatted I/O is a contract between a format string and extra arguments. A mismatch is undefined (often a crash or garbage), not a compile error.
printf("%s %d\n", name, n);
fprintf(stderr, "usage: %s <file>\n", argv[0]);
| Conversion | For |
|---|---|
%d / %i | int |
%u | unsigned int |
%ld / %lu | long / unsigned long |
%lld | long long |
%zu | size_t |
%f / %g | double (floats promote) |
%c | int (a character promoted) |
%s | char * to a string (must be NUL-terminated) |
%p | void * |
%% | A percent sign |
printf returns the number of characters printed, or negative on error. Check it when the output matters.
int n;
if (scanf("%d", &n) != 1) {
/* failed conversion — do not use n */
}
&n). %s already expects a char *.scanf returns the number of conversions assigned. Always check it.%s stops at whitespace and will overflow the buffer. Use a width: %127s into char buf[128], or prefer fgets then parse.%d stays in stdin — same family of bugs as Java’s nextInt/nextLine.int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
char line[128];
if (fgets(line, sizeof line, stdin) != NULL) {
/* may contain '\\n' */
}
getchar returns int, not char, so EOF (−1) is distinct from a byte 0xFF.gets was removed in C11. Do not use it even if a compiler still has it.puts(s) writes the string and a newline. fputs(s, stdout) does not add a newline.printf("%d", (long)x) or %d for size_t.scanf("%d", n) missing &.printf("%s", p) when p is NULL or not terminated.getchar in a char and comparing to EOF.fflush(stdin) — undefined. Drain with a loop or scanf scanset, not fflush on input.printf).scanf / fgets return values before using the object.fgets + sscanf / strtol over raw scanf for interactive input.stderr. Data on stdout.getchar is an int.~ Good luck with your revision! ~