[英]fgetc Always returns EOF
在嘗試計算文本文件中的行數時,我注意到fgetc始終返回EOF。 該代碼在Freebsd 10上可用,但現在在Mac OSX上不可用。 我檢查了文件是否為空,不是,它的大小約為1 KB,包含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;
}
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 Thompson)
/* 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.