Read Text File in C: Simple Guide
In C language, you can use file operation functions from the standard library to read the contents of a text file. Below is a simple example code showing how to read the content of a text file and print it to the console.
#include <stdio.h>
int main() {
FILE *file;
char c;
// 打开文本文件
file = fopen("example.txt", "r");
if(file == NULL) {
printf("无法打开文件\n");
return 1;
}
// 逐个字符读取文件内容并打印到控制台
while((c = getc(file)) != EOF) {
putchar(c);
}
// 关闭文件
fclose(file);
return 0;
}
In the above code, we start by using the fopen() function to open a text file named example.txt in read-only mode (“r”). Next, we read the file content character by character using the getc() function, and then print each character to the console using the putchar() function. Finally, we close the file using the fclose() function.
Please note that you need to replace example.txt with the filename of the actual text file you want to read. Also, ensure that the file is located in the current working directory or provide the correct path.