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:

  1. open a file
FILE *file = fopen("filename.txt", "r");
  1. 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;
}
  1. Reads a character from the specified file stream.
  2. Reads a character from a file.
  3. end of file
int ch;
while ((ch = fgetc(file)) != EOF) {
    // 处理读取到的字符
}
  1. 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;
}
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds