2013-10-29 51 views
0

所以在我的文件,該文件會保存在我的計劃顯示像計數長度

name name number 
name name number 
name name number 
name name number 
name name number 

我需要在該文件中元素的個數,所以在這種情況下,它應該是5

FILE *pRead; 

int num = 0; 

pRead = fopen("names.dat", "r"); 

if (pRead == NULL) 

printf("\nFile cannot be opened\n"); 

else 



while (!feof(pRead)) { 

num++ //add one to num 
printf("Num = ",num); //pint the value of num 

} //end loop 

這就是我所嘗試的,但它無限循環。

+3

爲什麼它會停止,如果你沒有讀什麼? –

+0

@ MichaelKrelin-hacker它正在閱讀names.dat – SolidCloudinc

+2

不,你只是檢查feof是「true」還是「false」,但沒有fread或fgetc或任何「消耗」字節...... – ShinTakezou

回答

0

你需要從你的循環讀取文件:

char buf[500]; 

while (!feof(pRead)) { 
    fgets(buf, 500, pRead); // Read another line from the file 
    num++ //add one to num 
    printf("Num = ",num); //pint the value of num 

} //end loop 
0

你好,你打開該文件,但也沒有看過。意味着文件指針停留在文件的開頭,所以你的循環不會終止。 您可以將其更改爲;

char line[100]; //Assuming max. length of one line is 100 

while(fgets(line, 100, pRead) != NULL) 
{ 
    //process the read data "line array" here 
}