2014-04-02 64 views
0

我試圖在c中打印一個文件的某一行。到目前爲止,我認爲我成功閱讀了我的文本文件的第8行,但是我的問題是如何使用此代碼打印該行?在c中打印某個文件的某一行

謝謝!

這是迄今爲止代碼:

int lineNumber = 8; 

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) 
     { 
      //use line or in a function return it 
      //in case of a return first close the file with "fclose(file);" 
     } 
     else 
     { 
      count++; 
     } 
    } 
    fclose(file); 
} 
+0

只需添加一個'printf(「%s」,line);'。 – ooga

+0

我試過,但它口口聲聲說該行是未定義:( – user3320997

+0

你要打印的同時,內部循環。 – ooga

回答

1

這工作完全正常。

是否缺少的主要功能還是隻是代碼片段,你已經張貼?

int lineNumber = 8; 

static const char filename[] = "Text.txt"; 

int main() 
{ 

    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) 
      { 
       //use line or in a function return it 
       //   //in case of a return first close the file with "fclose(file);" 
      printf("\n str %s ", line); 
      fclose(file); 
      return 0; 

      } 
      else 
      { 
       count++; 
      } 
     } 
     fclose(file); 
    } 
return 0; 

} 
相關問題