Read File in C: Code Examples with fread & fgets
In C language, one can use the standard library functions fread() or fgets() to read data from a file. Here are two common methods for reading data from a file:
- Reads a file in C programming.
#include <stdio.h>
int main() {
FILE *fp;
int data[100];
// 打开文件
fp = fopen("data.txt", "rb");
// 从文件中读取数据
fread(data, sizeof(int), 100, fp);
// 关闭文件
fclose(fp);
return 0;
}
- read user input
#include <stdio.h>
int main() {
FILE *fp;
char buffer[255];
// 打开文件
fp = fopen("data.txt", "r");
// 从文件中读取数据
while (fgets(buffer, sizeof(buffer), fp)) {
// 处理每行数据
printf("%s", buffer);
}
// 关闭文件
fclose(fp);
return 0;
}
In the examples above, data.txt is the name of the file to be read. In the first example, the fread() function will read 100 int type data consecutively into the array called “data”. In the second example, the fgets() function will read the data in the file line by line, reading one line at a time until the end of the file.