[英]Using fscanf() to read file line by line including whitespaces
我需要使用 fscanf 逐行讀取 c 中的文本文件(是的,我知道, fgets() 對此更好,但這是一個人為的分配)。 文件中的數據格式如下(忽略引號):
"firstname lastname"|100|500|300
"otherfirstname otherlastname"|150|450|120
etc...
每個點將被讀作, fscanf(fp, "%s|%d|%d|%d\\n", buf, &int1, &int2, &int3);
但是,上述方式有效,字符串將僅作為第一個單詞(名字)被讀取,而第二個單詞將被排除在外。 我試過使用 [^\\n] 但我最終只是無限打印文件中的第一行。
我想知道的是使用與上述類似的語句逐行遍歷文件的最佳方法,它可以讀取帶有空格的整個字符串而不會破壞其他所有內容。
這個給你。 為簡單起見,使用sscanf
而不是fscanf
。
#include <stdio.h>
int main(void)
{
const char *buf = "firstname lastname|100|500|300 \n"
"otherfirstname otherlastname |150|450|120 \n";
char name[100];
int x, y, z;
int offset = 0;
while ( sscanf( buf, "%[^|] | %d | %d | %d%n", name, &x, &y, &z, &offset ) == 4 )
{
buf += offset;
sscanf( buf, "%*[^\n]%n", &offset );
buf += offset;
sscanf( buf, "%*c%n", &offset );
buf += offset;
printf( "%s, %d, %d, %d\n", name, x, y, z );
}
return 0;
}
程序輸出是
firstname lastname, 100, 500, 300
otherfirstname otherlastname , 150, 450, 120
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.