簡體   English   中英

解析txt文件

[英]Parsing a txt file

我試圖解析一個包含格式名稱的txt文件:

"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH",...

這是我寫的代碼:


#include <stdio.h>
// Names scores
int problem22() {
    FILE *f = fopen("names.txt", "r");
    char name[100];
    fscanf(f, "\"%[^\"]s", name);
    printf("%s\n", name); // MARY
    fscanf(f, "\"%[^\"]s", name);
    printf("%s\n", name); // ,
    fscanf(f, "\"%[^\"]s", name);
    printf("%s\n", name); // PATRICIA
    return 0;
}

int main() {
    problem22();
    return 0;
}

每個對fscanf替代調用都給了我一個名字,而另一個則在獲取逗號時浪費了。 我嘗試了幾種格式,但我無法弄清楚如何做到這一點。

任何人都可以用正確的格式幫助我嗎?

我總是喜歡使用strtok()strtok_r()函數來解析文件。 (或者更喜歡使用一些csv庫)。

但只是為了好玩,我寫了一個代碼可能你喜歡它,我不是在我的答案中發布代碼但是檢查@codepad輸出,僅適用於特定格式。

使用strtok()

我認為正確的方法如下:

int main(){
// while(fp, csv, sizeof(csv)){   
    // First read into a part of file  into buffer
    char csv[] = "\"MARY\",\"PATRICIA\",\"LINDA\",\"BARBARA\",\"ELIZABETH\"";
    char *name = "", 
       *parse = csv;
    while(name = strtok(parse, "\",")){
        printf(" %s\n", name);
        parse = NULL;
    }
    return 0;
} // end while 

檢查codepade輸出:

 MARY
 PATRICIA
 LINDA
 BARBARA
 ELIZABETH

我建議在第二個代碼中繪制一個外部循環來讀取從文件到臨時緩沖區的行,然后應用像上面這樣的strtok()代碼: while(fgets(fp, csv, sizeof(csv))){ use strtok code}

將輸入格式字符串更改為"%*[,\\"]%[^\\"]"將執行您想要的操作:

fscanf(f, "%*[,\"]%[^\"]", name);
printf("%s\n", name); // MARY
fscanf(f, "%*[,\"]%[^\"]", name);
printf("%s\n", name); // PATRICIA
fscanf(f, "%*[,\"]%[^\"]", name);
printf("%s\n", name); // LINDA

%*只是跳過匹配的輸入。

你必須使用fseek()

此代碼成功運行:

#include <stdio.h>
#include <string.h>

int problem22()
{
    FILE *f = fopen("names.txt", "r");
    char name[100];
    int pos = 0, maxnames = 4, n;

    for(n = 0; n <= maxnames; n++)
    {
        fseek(f, pos, 0);
        fscanf(f, "\"%[^\"]s", name);
        printf("%s\n", name);
        pos += (strlen(name) + 3);
    }
    return 0;
}

int main()
{
    problem22();
    return 0;
}

您可以使用strtok()讀取整行並使用delin字符串將其拆分為標記","

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

// Names scores
int problem22() {
    FILE *f = fopen("file", "r");
    char *tok=NULL;
    char name[100];
    fscanf(f,"%s",name);

    printf("string before strtok(): %s\n", name);
    tok =  strtok(name, ",");
    while (tok) {
        printf("Token: %s\n", tok);
        tok = strtok(NULL, ",");
    }


return 0;
}

int main() {
    problem22();
    return 0;
}

注意: strtok()函數在解析時使用靜態緩沖區,因此它不是線程安全的。 如果這對您很重要,請使用strtok_r()

man strtok_r

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM