字符I/O流:
getchar函数族用于从流中读取一个字符:
int getchar(void);
int getc(FILE *fp);
int fgetc(FILE *fp); 返回值判断不等于EOF;
上述函数返回值为int型,其原因是为了允许函数报告文件的末尾(EOF)。
putchar函数族用于吧单个字符写入到流中:
int putchar(int character);
int putc(int character, FILE *fp);
int fputc(int character, FILE *fp); 返回值判断不等于EOF;
#include <stdio.h>
#include <stdlib.h>
int my_getchar(void); /*getchar、putchar函数*/
int my_getc(void); /*getc、putc函数*/
int my_fgetc(void); /*fgetc、fputc函数*/
int main(int argc, char *argv[]) /*字符I/O流的练习*/
{
my_getchar();
my_getc();
my_fgetc();
return 0;
}
int my_getchar()
{
char character = '0';
printf("input a character:"); /*getchar、putchar函数*/
character = getchar();
putchar(character);
putchar('\n');
return 0;
}
int my_getc() /*getc、putc函数*/
{
char character = 'A';
char other = '0';
FILE *file = NULL;
file = fopen("file.txt", "w+"); /*创建putc的文件流*/
if(file == NULL){
perror("fopen error: ");
exit(EXIT_FAILURE);
}
putc(character, file);
fclose(file);
file = fopen("file.txt", "a+"); /*创建getc的文件流*/
if(file == NULL){
perror("fopen error: ");
exit(EXIT_FAILURE);
}
other = getc(file);
printf("getc of the file:");
putchar(other);
putchar('\n');
fclose(file);
return 0;
}
int my_fgetc() /*fgetc、fputc函数*/
{
char character = 'B';
char other = '0';
FILE *file = NULL;
file = fopen("file.txt", "w+"); /*创建fputc的文件流*/
if(file == NULL){
perror("fopen error: ");
exit(EXIT_FAILURE);
}
fputc(character, file);
fclose(file);
file = fopen("file.txt", "a+"); /*创建fgetc的文件流*/
if(file == NULL){
perror("fopen error: ");
exit(EXIT_FAILURE);
}
other = fgetc(file);
printf("fgetc of the file:");
putchar(other);
putchar('\n');
fclose(file);
return 0;
}
/*getc和fgtc、putc和fputc在使用上没有太大的区别,只是实现上不同,
所以在使用时可以根据自己喜好选择。*/