How to Read a File in C
In C programming language, you can use the following method to read file contents and output them:
- open a file
FILE *file = fopen("filename.txt", "r");
- Check if the file has been successfully opened: Use a file pointer to perform a null check to ensure that the file has been opened successfully. For example:
if (file == NULL) {
printf("无法打开文件");
return 1;
}
- read input from a file
- Reads a line from the specified file.
- use the printf function
- Read line by line using the fscanf() function.
char line[100];
while (fscanf(file, "%s", line) != EOF) {
printf("%s\n", line);
}
- Read line by line using the fgets() function.
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
- Close the file.
fclose(file);
Complete code example:
#include <stdio.h>
int main() {
FILE *file = fopen("filename.txt", "r");
if (file == NULL) {
printf("无法打开文件");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}
Please ensure that the file exists and has the correct path before opening it. Additionally, the content read from the file will depend on its format and content type.