2013-09-16 38 views
0

如何在C讀取文件時給定的輸入格式爲讀取文件針對特定的輸入格式

4 
5 
3 
a,b 
b,c 
c,a 

請幫助...這是我的文件掃描功能。這裏m應該存儲4,n應該存儲5並且l應該存儲3.然後col1將存儲{abc}和col2將存儲{bca} m n,l是int。 col1和col2是char數組 該文件的第三行指示值3,表示它下面有三行,它包含3對字符。

i = 0, j = 0; 
while (!feof(file)) 
{ 
    if(j==0) 
    { 
    fscanf(file,"%s\t",&m); 
    j++; 
    } 
    else if(j==1) 
    { 
    fscanf(file,"%s\t",&n); 
    j++; 
    } 
    else if(j==2) 
    { 
    fscanf(file,"%s\t",&l); 
    j++; 
    } 
    else 
    { 
    /* loop through and store the numbers into the array */ 
    fscanf(file, "%s%s", &col1[i],&col2[i]); 
    i++; 
    } 
} 

,但我的結果是不是來告訴如何進行....

+0

該文件是否總是6行? – Floris

+0

第三行沒有值3,表示它下面有三行,它包含字符對。 –

+0

你正在走錯這條路。刪除'while'循環。然後編寫代碼來處理第一行。只能使用while循環來處理以相同方式處理的行(使用col1') – dcaswell

回答

2

修訂允許線

#include <stdio.h> 
#include <stdlib.h> 

int main(void) { 
    int value1, value2, value3, i; 
    char *col1, *col2; 
    char lineBuf[100]; 
    FILE* file; 

    file = fopen("scanme.txt","r"); 

    fgets(lineBuf, 100, file); 
    sscanf(lineBuf, "%d", &value1); 
    fgets(lineBuf, 100, file); 
    sscanf(lineBuf, "%d", &value2); 
    fgets(lineBuf, 100, file); 
    sscanf(lineBuf, "%d", &value3); 

    // create space for the character columns - add one for terminating '\0' 
    col1 = calloc(value3 + 1, 1); 
    col2 = calloc(value3 + 1, 1); 

    for(i = 0; i < value3; i++) { 
    fgets(lineBuf, 100, file); 
    sscanf(lineBuf, "%c,%c", &col1[i], &col2[i]); 
    } 
    fclose(file); 

    printf("first three values: %d, %d, %d\n", value1, value2, value3); 
    printf("columns:\n"); 
    for (i = 0; i < value3; i++) { 
    printf("%c %c\n", col1[i], col2[i]); 
    } 

    // another way of printing the columns: 
    printf("col1: %s\ncol2: %s\n", col1, col2); 
} 

我執行沒有平時的錯誤檢查等可變數量的閱讀 - 這只是爲了演示如何在讀的東西這產生預期的輸出。用你的測試文件。我希望你能從這裏拿下。

+0

而不是for循環中的3。如果我使用value3。您的代碼無法正常工作。我的觀點是第三行會告訴我在它後面會有多少個字符對。第三行是3,字符對的數量不會是3。 –

+0

請解釋你在說什麼。這適用於您提供的文件(3個數字後跟3行);如果你預計行數是可變的,你需要在你的問題中解釋這一點。 – Floris

+0

我現在明白了。我會相應地修改代碼。給我一分鐘。 – Floris

2

幾個要點:

  1. 不要使用feof(),它永遠需要這樣的代碼。
  2. 立即閱讀全文,fgets()
  3. 然後使用例如分析線來解析線。 sscanf()
  4. 從I/O函數檢查返回值,它們可能會失敗(例如在文件末尾)。