How to read data from a file in the C language?

In C language, you can open a file using the fopen() function and then read the data from the file using the fscanf() or fgets() functions.

Here is a straightforward example code that demonstrates how to read data from a file.

#include <stdio.h>

int main() {
   FILE *fp;
   char buffer[255];

   // 打开文件
   fp = fopen("文件路径", "r");

   // 检查文件是否成功打开
   if (fp == NULL) {
      printf("无法打开文件!\n");
      return 1;
   }

   // 逐行读取文件内容
   while (fgets(buffer, sizeof(buffer), fp) != NULL) {
      printf("%s", buffer);
   }

   // 关闭文件
   fclose(fp);

   return 0;
}

In the example above, the fopen() function is used to open a file, with the first parameter being the file path and the second parameter being the mode of opening the file (such as r for read-only). If the file opening fails, the fopen() function will return NULL.

Next, use the fgets() function to read the contents of the file line by line in a loop until the end of the file (when fgets() returns NULL). The first parameter of the fgets() function is the character array used to store the read data, the second parameter is the size of the character array, and the third parameter is the file to be read.

Close the file after finishing the file reading using the fclose() function.

Please note that the file path in the above example should be replaced with the actual file path and ensure that the file exists.

bannerAds