7.6. getchar() and putchar()¶
-
getchar
()¶
-
putchar
()¶
In addition to scanf() and printf(), two additional input-output
functions that are useful in some situations are getchar()
and
putchar()
.
Since char
values are stored as an int
,
getchar()
returns an int
.
Here is an example that can read the standard input and write all
capital letters to the standard output. The reason for calling
fflush(stdout);
is to force any characters that are still on the
output buffer to display immediately.
#include <stdio.h>
int main(void)
{
int c;
while((c = getchar()) != EOF )
putchar(toupper(c));
fflush(stdout);
return 0;
}
7.7. fgetc() and fputc()¶
-
fgetc
()¶
-
fputc
()¶
fgetc()
and fputc()
, work the same as getchar()
and
putchar()
except they take an extra argument for an open file descriptor.
#include <stdio.h>
int main(void)
{
FILE *rfp, *wfp;
int c;
if ((rfp = fopen("fileToRead", "r")) == NULL) {
printf("Cannot open file to read");
return 1;
}
if ((wfp = fopen("fileToWrite", "w")) == NULL) {
printf("Cannot open file to write");
return 1;
}
while((c = fgetc(rfp)) != EOF)
fputc(c, wfp);
fclose(rfp);
fflush(wfp);
fclose(wfp);
}