How can the file content be displayed in the C programming language?
To display the contents of a file in C language, you can follow these steps:
- open a file
 
FILE *fp;
fp = fopen("filename.txt", "r");
- if
 - There is no answer.
 
if (fp == NULL) {
    printf("Failed to open file.\n");
    return 1;
}
- reads a line from a file/stream.
 - Read the next character from the input stream
 
char buffer[255];
while (fgets(buffer, 255, fp) != NULL) {
    printf("%s", buffer);
}
Alternatively, use the fgetc() function.
int c;
while ((c = fgetc(fp)) != EOF) {
    printf("%c", c);
}
- Close file.
 
fclose(fp);
The complete example code:
#include <stdio.h>
int main() {
    FILE *fp;
    char buffer[255];
    
    fp = fopen("filename.txt", "r");
    if (fp == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }
    
    while (fgets(buffer, 255, fp) != NULL) {
        printf("%s", buffer);
    }
    
    fclose(fp);
    
    return 0;
}
Please note that the above code is only suitable for read-only files. If you want to write to a file, use the second parameter of the fopen() function as “w” or “a”.