How to open a file and read data in C language?
In C language, you can open a file using the fopen function and read data using the fscanf or fgets function.
Here is an example:
#include <stdio.h>
int main() {
FILE *file; // 文件指针
char buffer[100]; // 用于存储读取的数据
file = fopen("file.txt", "r"); // 打开名为file.txt的文件以读取数据
if (file == NULL) { // 检查文件是否成功打开
printf("无法打开文件\n");
return 1;
}
// 使用fscanf函数读取文件中的数据
// %s表示读取字符串,%d表示读取整数,%f表示读取浮点数等
while (fscanf(file, "%s", buffer) != EOF) {
printf("%s\n", buffer);
}
// 使用fgets函数逐行读取文件中的数据
// fgets函数的第一个参数为用于存储读取数据的字符数组,第二个参数为字符数组的大小,第三个参数为文件指针
// fgets函数会读取一行数据,包括换行符,并将其存储在字符数组中
// 当读取到文件末尾时,fgets函数返回NULL
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file); // 关闭文件
return 0;
}
In the above example, the fopen function opens a file named file.txt to read data, using “r” as the second parameter to indicate opening the file in read-only mode. If the file is successfully opened, the fopen function returns a file pointer, otherwise it returns NULL.
Using the fscanf function allows for reading data from a file in a specified format, whereas the fgets function can read data from a file line by line.
After reading the data from the file, it is necessary to use the fclose function to close the file and release resources.