不要混合fgets()
与fscanf()
直到你非常舒适与这些功能。他们在一起打球不好。在格式\n
是一种白色的空间和将匹配任何数量的连续白色空间,包括多个\n
,空格,制表符,等等
// fscanf(fin, "%d\n", &zip);
推介避免feof()
并使用来自fgets()
的返回值。
feof()
直到尝试读取文件并且未能提供char
才会成为真。这不同于“当没有人离开时是真的”。例如:您读取文件的最后一个char
。 feof()
仍然是错误的。代码尝试读取更多(并失败)。 现在feof()
是正确的。 (并保持真实)。
是否以简单的方式计算线条并使用对称性。进一步考虑更多错误检查。将邮政编码行读取为一个字符串,然后然后将其解析为一个整数。
int countLines(FILE * fin){
int count=0;
char street[100];
char city[100];
char state[100];
char zips[100];
unsigned zip;
while (fgets(street, sizeof street, fin) != NULL) {
count++;
}
rewind(fin);
if (count%4 != 0) Handle_LineCountNotMultipleof4();
// You could return here, but let's read the file again and get the data.
// This is likely part of OP's next step.
for (int i=0; i<count; i += 4) {
if ((NULL == fgets(street, sizeof street, fin)) ||
(NULL == fgets(city, sizeof city, fin)) ||
(NULL == fgets(state, sizeof state, fin)) ||
(NULL == fgets(zips, sizeof zips, fin)) ||
(1 != sscanf(zips, "%u", &zip))) handle_error();
// Remember street, city, state, still have an ending \n
do_something(street, city, state, zip);
}
return count;
}
或者,要计算行数,请使用以下内容。如果排队很长,在阅读中会出现奇怪的困难,所以让我们一起检查一下。如果你喜欢简单的答案,拿出这个东西line length
东西。您可以使用Maxline+1
作为缓冲区大小而不是固定的100.
size_t Maxline = 0;
size_t Curline = 0;
int ch;
while ((ch = fgetc(fin)) != EOF) {
Curline++;
if (ch == '\n') {
count++;
if (Curline > Maxline) MaxLine = Curline;
Curline = 0;
}
}
if ((Maxline + 1) > 100) TroubleAhead() ; // Trouble with future (fgets(buf, 100, fin), use bigger buffers
rewind(fin);
fgets读取整行直到文件或换行符结束。你的“String String String int”值是一行一行还是一行一行? – tyilmaz
这是每个条目的一行。 字符串\ n 字符串\ n 字符串\ n int \ n – kevorski
对于结果代码,不应检查任何*这些fgets()调用,也不要检查fscanf()是否应放在列表顶部“what-i'm-doing-wrong”,之后不久,通过在while循环中使用'feof()'作为中断条件,[这几乎总是错误的。](http://stackoverflow.com/问题/ 5431941/while-feof-file-is-always-wrong) – WhozCraig