How can you iterate over all the contents of a file in the C language?
In C language, you can use the fgetc() function to iterate through all the content of a file. The specific steps are as follows:
- open a file
FILE *file = fopen("filename.txt", "r");
- Check if the file has been successfully opened. If the file pointer is null, it means the file opening has failed.
if (file == NULL) {
printf("文件打开失败!\n");
return;
}
- Reads a character from the specified file stream.
- Reads a character from a file.
- end of file
int ch;
while ((ch = fgetc(file)) != EOF) {
// 处理读取到的字符
}
- close the file
fclose(file);
The complete example code is as follows:
#include <stdio.h>
int main() {
FILE *file = fopen("filename.txt", "r");
if (file == NULL) {
printf("文件打开失败!\n");
return 1;
}
int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // 示例:将读取的字符输出到屏幕上
}
fclose(file);
return 0;
}