2014-05-18 33 views
0

所以這只是一個簡單的從文件循環讀取,我似乎無法確定哪裏出了問題。我已經嘗試了很多方法,但似乎無法通過循環。我嘗試了很多方法進入(最初使用getc,但getc整個循環將被忽略。)從文件循環讀取 - 無法使用feof或getc進入循環

由於某種原因,它只是沒有爲我工作。下面的方式,程序凍結可能有人可以解釋爲什麼這樣,因爲文件指針應該指向文件的開頭,文件'input.txt'只是一個簡單的數據列表,我應該讀入一個結構,然後傳遞給另一個函數,輸入到我的數據結構中。

但是,我似乎甚至不能去其他函數。花了幾個小時試圖解決這個問題的不同方式。肯定有一個明顯的解決方案,我沒有看到。

void readWrite(char *inFile) 
{ 
    FILE *fp; 
    FILE *fpBin; 
    char c; 
    stuBucket temprec; 
    long address; 

    //open binary file to initialize hash file 
    if ((fpBin = fopen(BINARYFILE, "w+b")) == NULL) 
    { 
     printf("Could not open binary file %s.\n", BINARYFILE); 
     return; 
    } 
    fwrite(fpBin, sizeof(struct student), 50, fpBin); //Write entire hash table to disk 
    if (fp = fopen(inFile, "r") == NULL)  //open text file to read in from 
    { 
     printf("Could not open input file %s.\n", inFile); 
     return; 
    } 
    printf("Input File %s Open.\n", inFile); 

在下面

while(!feof(fp)) 
    { 
     printf("hello"); 
     fscanf(fp, "%d %s %s %f\n", temprec.stuID, temprec.lastName, 
            temprec.firstName, &temprec.amount); 
     writeRecord(temprec); 
     insert(temprec, fpBin); //hash data to disk 
     printf("insert done\n"); 
    } 
    fclose(fp); 
    fclose(fpBin); 
}//end readFromFile 

備用while循環問題,而被跳過的input.txt中

6745 SMITH ANNA 7769.87 
5675 JOHNSON SHEILA 23.91 
1235 WILLIAMS JANE 93.12 
2341 JONES BARBARA 74.23 
8624 BROWN YELENA 56.75 
9162 DAVIS SUSAN 902.34 
7146 MILLER ALISON 8934.12 
2328 WILSON ROYCE 123.09 
1622 MOORE TONI 83.65 
1832 TAYLOR JOAN 293.18 
3271 GARCIA ROBERT 43.72 
4717 MARTINEZ JHON 85.11 
9345 ROBINSON ANDRE 15.67 
1623 CLARK VICTOR 83.45 
5673 HALL MARC 93.13 
6275 ALLEN RAY 958.34 
5392 HERNANDEZ MICHAEL 23.45 
+0

請編輯該問題,並添加示例'inFile'的幾行。 –

+4

1)將'char c;'改爲'int c;'2)feof()不會做你想做的事情,最好暫時避免它。 – wildplasser

+0

@MahonriMoriancumer完成。只是提醒所有人:我甚至不能進入循環。這是主要問題,而不是實際循環的內容 - 雖然它可能有錯誤我可以處理。 – lloyd

回答

2

你的一個問題是:

if (fp = fopen(inFile, "r") == NULL) 

應該(當然)是:

if ((fp = fopen(inFile, "r")) == NULL) 

這則匹配在哪裏打開二進制文件。

+0

就是這樣。在使用作業時,我並不知道括號的確切用法。對我來說,這是一種新的語法,因爲到目前爲止,我一直在不同的線路上進行操作。謝謝。 – lloyd

1

c = getc(fp); 
while(c != EOF) 
{ 
    ungetc(c, fp); 
    printf("hello"); 
    fscanf(fp, "%d %s %s %f\n", temprec.stuID, temprec.lastName, 
           temprec.firstName, &temprec.amount); 
    writeRecord(temprec); 
    insert(temprec, fpBin); //hash data to disk 
    printf("insert done\n"); 
    c = getc(fp); 
} 

內容在這種情況下,可以fscanf留下一些文件末尾的空格字符。一定要檢查多少個值通過的fscanf成功讀取:

if (fscanf(fp, "%d %s %s %d\n", ...) != 4) break;