2016-11-22 95 views
0

我試圖編寫一個程序來讀取文件,並輸出文件的行。它將從最後一行開始,然後打印第二行到最後一行,然後是最後一行,第二行到最後一行,然後是第三行到最後一行,依此類推。 ((c = fgetc(myFile)!= EOF))while((c = fgetc(myFile))!= EOF) 這是循環的條件, 代碼(c = fgetc ....)關閉。
有人可以幫我解決這個問題嗎?
謝謝。學習如何讀取和輸出文件中的行C

void tail(FILE* myFile, int num) //Tail function that prints the lines   
according to the user specified number of lines 
{ 
int start, line = 0, counter = 0; 
char c, array[100]; 

while((c = fgetc(myFile) != EOF)) 
{ 

    if(c=='\n') 
     line++; 
} 

start = line - num; //Start location 

fseek(myFile, 0, SEEK_SET); //Goes to the start of the file 

while(fgets(array, 100, myFile) != NULL) 
{ 
    if(counter >start) 
    { 
     printf("%s",array); //Prints the string 
    } 
    counter++; 
} 

fclose(myFile); //Closes the file 
} 

回答

0

第一個問題,我看到的是這個成語:

while((c = fgetc(myFile) != EOF)) 

有括號錯了,應該是:

while ((c = fgetc(myFile)) != EOF) 

此外,此計數:

start = line - num; //Start location 

有一個錯誤:

int start = line - num - 1; // Start location 

除此之外,你似乎陣列一般文本行處理過小:

與幾個風格調整全部放在一起,我們得到:

// Tail function that prints the lines 
// according to the user specified number of lines 

void tail(FILE *myFile, int num) 
{ 
    int line = 0; 
    char c; 

    while ((c = fgetc(myFile)) != EOF) 
    { 
     if (c == '\n') 
     { 
      line++; 
     } 
    } 

    int start = line - num - 1; // Start location 

    (void) fseek(myFile, 0, SEEK_SET); // Go to the start of the file 

    int counter = 0; 
    char array[1024]; 

    while (fgets(array, sizeof(array), myFile) != NULL) 
    { 
     if (counter > start) 
     { 
      fputs(array, stdout); // Print the string 
     } 
     counter++; 
    } 

    fclose(myFile); // Close the file 
}