2016-11-22 94 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 
}