text 从文件中读取字符并使用“fgetc()”存储它

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 从文件中读取字符并使用“fgetc()”存储它相关的知识,希望对你有一定的参考价值。

fgetc()

Reads an character from the file and store it in a char variable. If the first time use this function, the file pointer will start from the beginning of the file. After that, will start from the next character from the previous position.

* The related file pointer must be opened as "r" for reading, if not you will suffer an error.

char ch = fgetc(<file pointer>);

char ch = fgetc(ptr1); // read a character from the file pointer "ptr1" and store it into char variable "ch".


One way of practical use of fgetc():

The ability to get single characters from files, if wrapped in a loop, means we could read all the characters from a file and print them to the screen, one by one, essentially.

	char ch;
	while ((ch = fgetc(ptr)) != EOF)
		printf("%c", ch);

So in this line of code, will first read a char from the file and store it into variable "ch". Compare this "ch" with "EOF" to make sure it's not the end of the file. And print this char onto the screen using "printf()".

There is a Linux command "cat" that does this. If you type "cat filename" it will print out whole content of the file in your terminal window.

以上是关于text 从文件中读取字符并使用“fgetc()”存储它的主要内容,如果未能解决你的问题,请参考以下文章

c语言 如何读取中文字符串

算法练习

C语言 文件读写 fgetc 函数

线程和分叉:从 popen()-pipe 读取时 fgetc() 阻塞

字符(串)读写

C语言如何读取TXT全部字符?