博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

输入函数-getchar,getc,fgetc

Posted on 2023-03-13 05:58  乔55  阅读(153)  评论(0编辑  收藏  举报

getchar

// getchar详解
int getchar(void);
// getchar() return the character read as an  unsigned char cast to an int
//  or EOF on end of file or error

// 将读取一个无符号char类型字符转换为int后返回,
// 或返回EOF,表明读取失败,或到了file的末尾。该函数是从stdin中读取字符。

// getchar() is equivalent to getc(stdin).,意思是等同于 getc(stdin)
// int getc(FILE *stream);
int ch = getchar();
int ch = getc(stdin);

getc

// getc详解
int getc(FILE *stream);

// getchar() return the character read as an  unsigned char cast to an int 
// or EOF on end of file or error

// 将读取一个无符号char类型字符转换为int后返回,
// 或返回EOF,表明读取失败,或到了file的末尾。

int fgetc(FILE *stream);

// getc()  is equivalent to fgetc() ,except that 
// it may be implemented as a macro which evaluates stream more than once.
// getc()等价于fgetc(),除了getc可以被实现为宏这种情况

getc举例:

// getc.c:fopen打开一个文件,getc逐个字符读取该文件,并输出在stdout

int ch;
char fname[50];
printf("input the file name:");
scanf("%s",fname);
FILE* fp = fopen(fname,"r"):
if(fp == NULL)
{
  exit(1);
}
while((ch = getc(fp)) != EOF)
{
  putchar(ch);
}
fclose(fp);

fgetc

int fgetc(FILE *stream);

// fgetc() reads the next character from  stream  and  
// returns  it  as  an unsigned char cast to an int, 
// or EOF on end of file or error.

// 从stream指定文件流中读取下一个unsigned字符,并将读取到的字符转为int返回
// 或者返回EOF,表明读取到了文件流的末尾,或读取错误


fgetc举例

// 调用形式: ./target srcFile destFile
// 功能:将已存在的srcFile文件拷贝至destFile
// 拷贝后查看2文件是否一致:diff srcFile destFile

int main(int argc, char** argv)
{
	if(argc < 3)
	{
		fprintf(stderr, "Usage:%s <src_file> <dest_file>\n", argv[0]);
		exit(1);
	}
	FILE* fps = fopen(argv[1], "r");        // 以读方式打开源文件
	if(fps == NULL)
	{
		perror("fps = fopen()");
		exit(1);
	}
	FILE* fpd = fopen(argv[2], "w");        // 以写方式打开目的文件
	if(fpd == NULL)
	{
		fclose(fps);    // 若打开目的文件失败,程序结束,关闭fps
		perror("fpd = fopen()");
		exit(1);
	}
	int ch;    // 用来接收逐个读取的字符
	while(1)
	{
		ch = fgetc(fps);
		if(ch == EOF)
		{
			break;
		}
		fputc(ch, fpd);    // 将ch字符输出到fpd指向流中
	}
	fclose(fps);
	fclose(fpd);
	return 0;
}

fgetc举例

// 统计一个文件的字符个数
// 调用形式:./target srcfile

int main(int argc, char** argv)
{
	if(argc < 2)
	{
		fprintf(stderr, "Usage:%s <src_file>\n", argv[0]);
	}
	FILE* fp = fopen(argv[1], "r");
	if(fp == NULL)
	{
		perror("fopen()");
		exit(1);
	}
	int count = 0;
	while(fgetc(fp) != EOF)
	{
		count++;
	}
	printf("count=%d\n", count);
	fclose(fp);
	return 0;
}