2011-04-17 245 views
0

我有一個文件名爲todo.txt,我有一個函數,它會列出文件中的每一行:讀取文件時跳過行用C

void list() { 
    FILE *todoFile; 
    todoFile = fopen("./todo.txt", "r"); 
    char line[4096]; 
    int len; 

    if (todoFile != NULL) { 
     while (fgets(line, sizeof line, todoFile)) { 
      len = strlen(line); 
      if (len && (line[len - 1] != '\n')) { 
       printf("%s", line); 
      } 
      printf("%s", line); 
      fclose(todoFile); 
     } 
    } else { 
     printf("ERROR"); 
    } 

} 

todo.txt內容是:

* foo! 
* hello 
* FP! 

但當我使用list()功能時只打印第一行:

* foo! 

有什麼想法?

回答

3

您不能在封閉的文件上調用fgets()

0

您需要在之後關閉文件您已完成while循環中的讀取。

void list() { 
    FILE *todoFile; 
    todoFile = fopen("./todo.txt", "r"); 
    char line[4096]; 

    if (todoFile != NULL) { 
     while (fgets(line, sizeof line, todoFile)) { 
      printf("%s", line); 
     } 
     fclose(todoFile); 
    } else { 
     printf("ERROR"); 
    } 
} 
相關問題