How can C language read text from a file?
In C language, you can open a file using the fopen function and read text from the file using the fscanf function.
Below is a sample code that demonstrates how to read text line by line from a file and output it to the console:
#include <stdio.h>
int main() {
FILE *file;
char line[100];
// 打开文件
file = fopen("filename.txt", "r");
if (file == NULL) {
printf("无法打开文件!");
return 1;
}
// 逐行读取文件内容并输出
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
// 关闭文件
fclose(file);
return 0;
}
The fopen function in the above code is used to open a file named filename.txt in read-only mode (“r”). If the file cannot be opened, an error message will be displayed and 1 will be returned.
Next, use the fgets function to read text line by line from the file and store it in the line character array. The fgets function will stop reading when it reaches a newline character or the specified maximum number of characters. Then, use the printf function to output the read text to the console.
Finally, use the `fclose` function to close the file. This is a crucial step to ensure the file is properly closed and any associated resources are released.