2012-09-12 106 views
1

我有一個文件,我想逐行閱讀,但它必須動態完成,這意味着它應該只讀一行,當我打電話給方法。一旦我下次調用方法,它應該讀取文件的下一行,依此類推。 到目前爲止,我只能成功地讀取文件中的所有行,或者一次又一次地讀取同一行。從C文件中「動態」讀取文件,使用方法

這裏是我的代碼片段:

文件與方法:

int getNextData(){ 
static const char filename[] = "file.txt"; 
    FILE *file = fopen (filename, "r"); 
    if (file != NULL) 
    { 
     char line [ 5 ]; /* or other suitable maximum line size */ 

     if (fgets (line, sizeof line, file) != NULL) /* read a line */ 
     { 
     fputs (line, stdout); /* write the line */ 
     } 
    } 
    else 
    { 
     perror (filename); /* why didn't the file open? */ 
    } 
    return 0; 
} 

主要文件:

int main() { 
    // this should give me two different numbers 
getNextData(); 
    getNextData(); 
return 0; 
} 

我已經離開了 「有」,但這部分是正確的。

這種情況下的輸出是同一行兩次。

任何人都可以幫我嗎?

回答

3

問題很可能是您每次打開文件,從而重置文件指針。嘗試在主函數中只打開一次,然後將文件句柄傳遞給函數進行讀取。

這裏的一些修改的代碼應該爲你工作:

#include <stdio.h> 

int getNextData(FILE * file){ 

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

     if (fgets (line, sizeof line, file) != NULL) /* read a line */  
     {   
      fputs (line, stdout); /* write the line */  
     }  
    }  

    return 0; 
} 

int main() {  // this should give me two different numbers 
    static const char filename[] = "file.txt"; 
    FILE *file = fopen (filename, "r"); 
    getNextData(file);  
    getNextData(file); 
    return 0; 
} 

有了這個代碼,給定的文件:

[email protected]:~> ls -l file.txt 
-rw-r--r-- 1 mike users 15 Sep 11 18:18 file.txt 
[email protected]:~> cat file.txt 
bye 
sh 
ccef 

我看到:

[email protected]:~> ./a.out 
bye 
sh 
+0

我已經試過,但控制檯不打印任何東西。 – user1627114

+1

您是否包含''?你檢查過fopen的返回值嗎?它是什麼?與您的可執行文件位於同一目錄中的是「file.txt」嗎?你對文件有讀取權限嗎?那裏的線是否被換行符分隔? – Mike

+0

這與一些解決方法合作謝謝! – user1627114

0

你需要以某種方式維護狀態,在這種情況下,你所在的文件中,在調用之間。

最簡單的方法是讓FILE *住在:

int getNextData(void) { 
    static const char filename[] = "file.txt"; 
    static FILE *file = NULL; 

    if(file == NULL) 
    file = fopen (filename, "r"); 

    /* rest of function */ 
} 

注意,這是一個有點難看,這使得它不可能(因爲功能是void)到例如重新開始閱讀,當文件結束時會發生什麼?但這是最簡單的方法。你應該能夠建立在這個基礎上。

0

只是一個側記:你的任務是I/O相關的,但從你的描述來看,它看起來對你從文件讀取的數據沒有任何影響(除了從回聲中回來)。這可能會混淆適當的解決方案。

我會嘗試超越語言語法,關注預期的程序功能。在一種方法中,您可以定義一個程序狀態結構/句柄來包含文件指針,行號,緩衝區等。然後,您的函數將從句柄中獲取狀態並從文件中讀取下一行。

所以流量可能是: init(appstate, filename) ==> loop:{ read_file(appstate) ==> process_line(appstate) } ==> end(appstate)

這使得程序流程清晰,通過明確定義程序狀態使用靜態變量避免。