我正在编写一个程序,该程序读取几乎200万行的文件。该文件的格式为“整数ID”标签,带有艺术家姓名字符串。
6821361 Selinsgrove High School Chorus
10151460 greek-Antique
10236365 jnr walker & the all-stars
6878792 Grieg - Kraggerud, Kjekshus
6880556 Mr. Oiseau
6906305 stars on 54 (maxi single)
10584525 Jonie Mitchel
10299729 エリス レジーナ/アントニオ カルロス ジョビン
上面是一个示例,其中包含文件中的某些项目(某些行未遵循特定格式)。我的程序工作文件,直到到达示例的最后一行,然后不断打印エリス レジーナ/アントニオ カルロス ジョビ\343\203
。
struct artist *read_artists(char *fname)
{
FILE *file;
struct artist *temp = (struct artist*)malloc(sizeof(struct artist));
struct artist *head = (struct artist*)malloc(sizeof(struct artist));
file = fopen("/Users/Daniel/Library/Developer/Xcode/DerivedData/project_Audioscrobbler_Artists-hgwyqpinuoxayzbmvarcjxryqnrz/Build/Products/Debug/artist_data.txt", "r");
if(file == 0)
{
perror("fopen");
exit(1);
}
int artist_ID;
char artist_name[650];
while(!feof(file))
{
fscanf(file, "%d\t%65[^\t\n]\n", &artist_ID, artist_name);
temp = create_play(artist_ID, artist_name, 0, -1);
head = add_play(head, temp);
printf("%s\n", artist_name);
}
fclose(file);
//print_plays(head);
return head;
}
上面是我从文件中读取的代码。您能帮忙解释一下哪里出了问题吗?
正如评论所指出的那样,while(!feof(file))的问题是链接的内容将详细解释为什么这不是一个好主意,但总的来说,引用链接中的答案之一:
(!feof(文件))...
...是错误的,因为它会测试不相关的内容,而不会测试您需要了解的内容。结果是您错误地执行了假定代码正在访问已成功读取的数据的代码,而实际上却从未发生过。-Kerrek SB
就您而言,这种用法不会引起您的问题,但是正如Kerrek解释的那样,请掩盖它。
您可以将其替换为fgets(...)
:
char lineBuf[1000];//make length longer or shorter for your purpose
file = fopen("/Users/Daniel/Library/Developer/Xcode/DerivedData/project_Audioscrobbler_Artists-hgwyqpinuoxayzbmvarcjxryqnrz/Build/Products/Debug/artist_data.txt", "r");
if(!file) return -1;
while(fgets (lineBuf, sizeof(lineBuf), file))
{
//process each line here
//But processing Japanese characters
//will require special considerations.
//Refer to the link below for UNICODE tips
}
特别是,您将需要使用足以包含将要处理的不同大小字符的变量类型。该链接对此进行了详细讨论。
这是节选:
"char" no longer means character I hereby recommend referring to character codes in C programs using a 32-bit unsigned integer type. Many platforms provide a
“ wchar_t”(宽字符)类型,但是不幸的是,要避免使用它,因为某些编译器仅分配16位,不足以表示Unicode。无论何时需要传递单个字符,都可以将“ char”更改为“ unsigned int”或类似字符。“ char”类型的唯一剩余用途是表示“ byte”。
编辑:
在上面的注释中,您声明但失败的字符串是66个字节长。因为您正在读一个'char'数组,所以完成字符所需的字节在包含最后一个必需字节之前被截断了一个字节。ASCII字符可以包含在一个char
空格中。日语字符不能。如果您使用的是unsigned int
而不是的数组char
,则最后一个字节将被包括在内。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句