我正在编写一个函数来读取给定文件并将其内容打印到屏幕上。目前我有以下内容:
int textdump(const char *filename)
{
int n = 0;
char ch;
FILE *fileHandle;
fileHandle = fopen(filename, "r");
if ((fileHandle = fopen(filename, "r")) == NULL)
{
return -1;
fclose(fileHandle);
}
while ((ch = fgetc(fileHandle) != EOF) )
{
printf("%c", ch);
n++;
}
fclose(fileHandle);
if (fclose(fileHandle) == EOF)
{
return EXIT_FAILURE;
}
return n;
}
该函数成功读取文本文件并正确返回每个文件中的字符数。但后来我尝试打印字符,现在我甚至无法运行程序 - 我得到“运行失败 - doc不能为null,无法解析测试结果”。
答案 0 :(得分:6)
总结上述代码的问题,
fopen()
/ fclose()
两次?摆脱那部分。 ---------------(1)fclose()
尚未打开的内容。 ----------------------------------------------(2)< / LI>
return
之后的所有陈述都没有效果。 -------------------------------------------------- ----(3)fgetc()
时照顾operator precedence。 -----------------------------------------(4)fgetc()
返回int
值。相应地改变。 -----------------------------------------------(5) 所以,你的代码看起来像
int textdump(const char *filename)
{
int n = 0;
int ch = 0;
FILE *fileHandle = NULL;
//fileHandle = fopen(filename, "r"); //not reqd --- (1)
if ((fileHandle = fopen(filename, "r")) == NULL){
return -1;
//fclose(fileHandle); // not reqd --- (2), (3)
}
while ( (ch = fgetc(fileHandle)) != EOF ){ //notice here -- (4), (5)
printf("%c", ch);
n++;
}
fclose(fileHandle);
/*
if(fclose(fileHandle) == EOF){ -- (1)
return EXIT_FAILURE;
}*/
return n;
}
答案 1 :(得分:4)
while ( (ch = fgetc(fileHandle) != EOF) )
应该是
while ( (ch = fgetc(fileHandle)) != EOF)
您需要注意运营商优先级。发布的代码ch = fgetc()
将不会被您首先评估,因此请添加括号以确保将它们绑定在一起,如上所示。
答案 2 :(得分:4)
int textdump(const char *filename)
{
int n = 0;
FILE *fileHandle;
/* char ch; fgetc wants an int (able to store EOF) not a char */
int ch;
fileHandle = fopen(filename, "r");
if (fileHandle == NULL){
/* return -1; */
/* fclose(fileHandle); */
/* you can not close what is not oppened */
perror("fopen");
return -1;
}
while ((ch = fgetc(fileHandle)) != EOF) /* Beware of the precedence */
printf("%c", ch);
n++;
}
/* You don't need to check the result of fclose
if(fclose(fileHandle) == EOF){
return EXIT_FAILURE;
}
*/
fclose(fileHandle);
return n;
}
答案 3 :(得分:0)
这应该足够了
int textdump(const char * filename) {
int n = 0, c;
FILE * fp = fopen(filename, "r");
if (fp == NULL) return -1;
while ((c = fgetc(fp)) != EOF) putchar(c), n++;
fclose(fp);
return n;
}