简体   繁体   中英

Creating a text file that could be read using c fscanf

This is my program using which I am trying to read a simple text file and store the output in an structure. The problem I am facing currently is on the while loop where it does not to work. File handle seems to read the file. Also, the input file has been created using a simple windows notepad with the given text - can this be a problem?

#include<process.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>

struct studyCentre {
    char stdCode[10], stdName[40], regName[40], coord[20], prgin[20], address[35], email[40], webs[45];
    int ph;
} std;

int flag=0;

void main() {
    FILE *fp;

    fp  = fopen("studyCentre.txt", "r+");
    if (fp==NULL) {
        printf("No file found");
        exit(0);
    }

    while(feof(fp)!=0) {
    //while(!fp.EOF()) {
        fscanf(fp, "%s%s%s%s%s%s%s%s%d", std.stdCode, std.stdName, std.regName, std.coord, std.prgin, std.address, std.email, std.webs, &std.ph);
        printf("\n Study Center Name :: %s \n Regional Centre Name :: %s \n Coordinator Name = %s \n Program incharge Name :: %s Address %s \n Email :: %s \n Website :: %s \n Phone :: %d", std.stdName, std.regName, std.coord, std.prgin, std.address, std.email, std.webs, &std.ph);
        flag=1;
    }
    if (flag==0) {
        printf ("No record found");
    }
    fclose(fp); 
}

Output

No record found

This is the text in my text file.

111
a
b
c
d
e
f
g
h
122

Edit: Corrected a typo.

Also you need to look at what the function feof is returning :

Return :

A non-zero value is returned in the case that the end-of-file indicator associated with the stream is set. Otherwise, zero is returned.

You should write

while(feof(fp)==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