2013-03-28 58 views
0

這是我正在使用的程序,我試圖讀取一個簡單的文本文件並將輸出存儲在結構中。我目前面臨的問題是在while循環中它不起作用。文件句柄似乎讀取文件。此外,輸入文件已使用給定文本使用簡單的Windows記事本創建 - 這可能是一個問題?創建可以使用c讀取的文本文件fscanf

#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); 
} 

輸出

No record found 

這是我的文本文件中的文本。

111 
a 
b 
c 
d 
e 
f 
g 
h 
122 

編輯:更正拼寫錯誤。

+0

不要響應答案編輯你的問題。這會導致混淆並使提供的答案無效。 – hmjd 2013-03-28 09:57:00

+0

這是一個錯字。我的實際程序是寫入。我爲這個錯誤道歉。 – abhig10 2013-03-28 09:58:53

+0

@ abhig10,檢查問題的標題,可能還有一個錯字。我想你想'fscanf'而不是'scanf'。 – Dipto 2013-03-28 10:05:19

回答

4

你也需要看看什麼功能FEOF將返回:

返回:

非零值的情況下返回與該流相關的檔案結尾指標組。 否則,返回零。

你應該寫

while(feof(fp)==0)