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:

  1. open a file
FILE *fp;
fp = fopen("filename.txt", "r");
  1. if
  2. There is no answer.
if (fp == NULL) {
    printf("Failed to open file.\n");
    return 1;
}
  1. reads a line from a file/stream.
  2. 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);
}
  1. 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”.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds