2014-04-02 94 views
0

我的程序從文件中正確讀取了特定行,但它從我指定的行中讀取整個文件。我試圖一次僅打印一行。我怎麼才能讓它只讀一行?從c代碼中的文件中讀取一行代碼

代碼:

int main() 
{ 
    int lineNumber = 5; 
    static const char filename[] = "Text.txt"; 
    FILE *file = fopen(filename, "r"); 
    int count = 0; 

    if (file != NULL) 
    { 
    char line[256]; /* or other suitable maximum line size */ 

    while (fgets(line, sizeof line, file) != NULL) /* read a line */ 
    { 
     if (count == lineNumber) 
     { 
      printf("%s", line); 
      //in case of a return first close the file with "fclose(file);" 
     } 
     else 
     { 
      count++; 
     } 
    } 
    fclose(file); 
    } 
} 
+0

查看鏈接http://rosettacode.org/wiki/Read_a_file_line_by_line –

回答

1

你找到所需的線路後,只需使用一個break退出循環:當你的行,你

if (count == lineNumber) 
{ 
    printf("%s", line); 
    break; 
} 
0
if (count == lineNumber) 
     { 
      printf("%s", line); 
      //in case of a return first close the file with "fclose(file);" 
      count++; 
     } 

增量count指定,否則count將不會繼續指示下一行。這就是爲什麼一旦你得到你指定的行,你的代碼就會打印所有的行。因爲線號count不會增加,一旦它變成等於linenumber。所以請加count++
您甚至可以使用break循環,因爲您不需要在獲取指定行後讀取其餘行。