在试图计算文本文件中的行数时,我注意到fgetc总是返回EOF。这段代码在Freebsd 10上运行,但现在它不在Mac上工作。我检查了这个文件,看看它是否是空的,它不是,它大约有1KB大小,包含16行。我在文件的开头添加了一行,认为这是问题所在,但它仍在返回EOF。那么为什么fgetc总是返回EOF呢?
int getLines(int listFd, int *lines)
{
/* Declarations */
*lines = 0;
int ch;
FILE *list;
/* Get File Stream */
list = fdopen(listFd, "r");
if(list == NULL)
{
printf("Can't Open File stream\n");
return -1;
}
/* Seek To beginning Of file */
fseek(list, 0, SEEK_SET);
/* Get Number of Lines */
while(!feof(list))
{
ch = fgetc(list);
if(ch == '\n')
{
lines++;
}
else if(ch == EOF)
{
break;
}
}
printf("lines: %d\n", *lines);
/* Clean up and Exit */
fclose(list);
return 0;
}发布于 2014-09-18 18:06:41
fgetc()最终应该返回EOF。代码的另一个问题当然是混淆了行为和诊断。很好地测试IO功能的结果。
int getLines(int listFd, int *lines) {
...
*lines = 0;
...
if (fseek(list, 0, SEEK_SET)) puts("Seek error");
...
ch = fgetc(list);
if (ch == '\n') {
// lines++;
(*lines)++; // @R Sahu
}
...
printf("lines: %d\n", *lines);
if (ferror(list)) puts("File Error - unexpected");
if (feof(list)) puts("File EOF - expected");
}其他东西:
下面的代码是对文件结束条件的冗余测试。
/* Get Number of Lines */
while(!feof(list)) {
ch = fgetc(list);
...
else if(ch == EOF) {
break;
}
}建议简化(@Keith )
/* Get Number of Lines */
while( (ch = fgetc(list)) != EOF) {
if(ch == '\n') {
(*lines)++;
}
}关于文件行计数的一些小问题:如果文件在最后的'\n'之后有文本,那么它会算作一行吗?建议:
*lines = 0;
int prev = '\n';
/* Get Number of Lines */
while( (ch = fgetc(list)) != EOF) {
if(prev == '\n') {
(*lines)++;
}
prev = ch;
}https://stackoverflow.com/questions/25918894
复制相似问题