简体   繁体   中英

How to read and display the contents of a .txt file using C?

How can I write a C program which can read the numbers and strings in a.txt file? I am just able to read a portion of text file till now.

在此处输入图像描述

#include <stdio.h>
#include <stdlib.h>

int main()

{
    char c[1000];
    FILE *fptr;
    if ((fptr = fopen("data3.txt", "r")) == NULL) 
    {
        printf("Error! opening file");
        exit(1);
    }

    fscanf(fptr, "%[]", c);
    printf("Data from the file:\n%s", c);
    fclose(fptr);

    return 0;
}

I have used another method to solve it.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE * txt;

    char ch;
    txt = fopen("nameOfTheFile.txt", "r"); 
    
    if(txt == NULL)
    {
        printf("Unable to open the file\n");
        exit(EXIT_FAILURE);
    }

    do 
    {
        ch = fgetc(txt);
        putchar(ch);

    } while(ch != EOF);
    
    fclose(txt);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM