Read Text File in C: Simple Example
In the C language, you can use file operation functions in the standard library to read the contents of a TXT file. Here is a simple example code:
#include <stdio.h>
int main() {
FILE *file;
char filename[] = "example.txt";
char buffer[100];
file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file.");
return 1;
}
while (fgets(buffer, 100, file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}
In the example above, we open a file named example.txt using the function fopen() with read-only mode. Then we use the function fgets() to read the file content line by line and print it to the console. Finally, we close the file using the function fclose().
Please make sure to replace “example.txt” with the actual filename you want to read, and ensure that the file exists in the current directory where the program is running.