C File Read: Open & Read Files
In C language, standard library functions can be used to open files and read data. Below is a simple example:
#include <stdio.h>
int main() {
FILE *file;
char data[100];
// 打开文件
file = fopen("example.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
// 读取数据
while (fgets(data, sizeof(data), file) != NULL) {
printf("%s", data);
}
// 关闭文件
fclose(file);
return 0;
}
In this example, the file named “example.txt” is first opened using the fopen function with the specified read-only mode (“r”). If the file opening fails, the program will print an error message and return 1.
Then, read data from the file using the fgets function and print it line by line. Finally, close the file using the fclose function.
It is important to always check if the file is successfully opened and closed during the file operation process, and to also perform validity checks on the data that is being read.