2017-08-29 69 views
1

當逐行掃描文本文件時,我希望能夠看到下一行並在當前行上進行檢查。我正在用C語言工作。我相信fseek()或其他類似的功能會幫助我,但我不確定,不知道如何使用它們。我想實現的東西的效果:如何在處理輸入文件時處理前進(處理2行)

fp = fopen("test-seeking.txt", "r"); 

    while((fgets(line, BUFMAX, fp))) { 
     // Peek over to next line 
     nextline = ...; 
     printf("Current line starts with: %-3.3s/Next line starts with %-3.3s\n", 
       line, nextline); 
    } 

我感謝所有幫助。

+0

使用'fgetc'和'ungetc'或只讀下一行。 –

+7

讀取1行,然後讀取一行並使用2深度緩衝區。緩衝區中的第一行是當前行,另一行是下一行。 –

+0

WINAPI具有Peek系列功能。 – iBug

回答

0

事實上,你可以使用fseek和嘗試是這樣的:

fp = fopen("test-seeking.txt", "r"); 

while ((fgets(line, BUFMAX, fp))) { 
    // Get the next line 
    fgets(nextline, BUFMAX, fp); 

    // Get the length of nextline 
    int nextline_len = strlen(nextline); 

    // Move the file index back to the previous line 
    fseek(fp, -nextline_len, SEEK_CUR); // Notice the - before nextline_len! 

    printf("Current line starts with: %-3.3s/Next line starts with %-3.3s\n", line, nextline); 
} 

另一種方法是使用fgetposfsetpos,像這樣:

fp = fopen("test-seeking.txt", "r"); 

while ((fgets(line, BUFMAX, fp))) { 
    // pos contains the information needed from 
    // the stream's position indicator to restore 
    // the stream to its current position. 
    fpos_t pos; 

    // Get the current position 
    fgetpos(fp, &pos); 

    // Get the next line 
    fgets(nextline, BUFMAX, fp); 

    // Restore the position 
    fsetpos(fp, &pos); 

    printf("Current line starts with: %-3.3s/Next line starts with %-3.3s\n", line, nextline); 
} 
+0

謝謝您的迴應! –

0

以下代碼受@Jean-François Fabrecomment啓發。它將使用用於保存線條的2D字符數組lineBuffer。第一條讀取行寫入索引0 lineBuffer[0],第二行寫入lineBuffer[1]。之後,這些着作在索引0和1之間交替,並在toggle variablelineSel的幫助下進行。作爲最後一步,curLine指針將被設置爲nextLine

因此,您可以在循環內使用curLinenextLine。 如果你有一個包含的文件:

line 1 
line 2 
line 3 
... 

您將與:

curLine = "line 1\n" 
nextLine = "line 2\n" 

curLine = "line 2\n" 
nextLine = "line 3\n" 

... 

live example with stdin instead of a file on ideone

代碼:

#include <stdio.h> 

#define BUFMAX  256 
#define CURLINE  0 
#define NEXTLINE  1 
#define TOGGLELINE (CURLINE^NEXTLINE) 

int main() 
{ 
    FILE* fp = fopen("test-seeking.txt", "r"); 

    char lineBuffer[2][BUFMAX]; 
    char* curLine; 
    char* nextLine; 
    int lineSel; 

    if (fp != NULL) 
    { 
     if ((curLine = fgets(lineBuffer[CURLINE], BUFMAX, fp))) 
     { 
     for (lineSel = NEXTLINE; 
       (nextLine = fgets(lineBuffer[lineSel], BUFMAX, fp)); 
       lineSel ^= TOGGLELINE) 
     { 
      printf("Current line: \"%s\"/Next line \"%s\"\n", 
        curLine, nextLine); 

      curLine = nextLine; 
     } 
     } 

     fclose(fp); 
    } 

    return 0; 
} 
+0

謝謝你對我的問題的迴應安德烈!我只是選擇了一個答案作爲解決方案。 –