问题描述
#include<stdio.h>
#include "file.h"
void openfilechk()
{
char ch;
fp = fopen("abc.txt","r");
while( ( ch = fgetc(fp) ) != EOF )
{
printf("%c",ch);
}
// fclose(fp);
printf("file readed \n");
if (fclose(fp) == 0)
{
//close was successful
// fp = 0; // this ensures you the file is closed
printf("\nFILE SUCCESSFULLY CLOSED\n");
}
}
int main()
{
openfilechk();
if (fp == NULL)
{
//close was successful
// fp = 0; // this ensures you the file is closed
printf("\nFILE SUCCESSFULLY CLOSED\n");
}
return 0;
}
main内的部分未验证文件是否已关闭?
file.h
FILE * fp;
portion inside main is not validating whether a file is closed?
file.h
FILE *fp;
推荐答案
#include<stdio.h>
#include "file.h"
void openfilechk()
{
char ch;
fp = fopen("abc.txt","r");
while( ( ch = fgetc(fp) ) != EOF )
{
printf("%c",ch);
}
printf("file readed \n");
if (fclose(fp) == 0)
{
//close was successful
fp = NULL; // this ensures you the file is closed
printf("\nFILE SUCCESSFULLY CLOSED\n");
}
}
int main()
{
fp = NULL; // Give it an initial value
openfilechk();
if (fp == NULL)
{
//close was successful
printf("\nFILE SUCCESSFULLY CLOSED\n");
}
return 0;
}
BTW:这是风格的东西,但我不会在.h文件中声明变量 - 常量和结构定义只有。
我也会从 openfilechk
方法返回 fp
并存储它在本地变量中而不是使用全局 - 这样您将来可以将它用于两个不同的文件。如果函数被定义为检查是否可以打开文件,我会返回 bool
而不是FILE * - 它会使你的代码成为更可读。
BTW: It''s a style thing, but I wouldn''t declare variables in a ".h" file - constants, and structure definitions only.
I''d also return fp
from the openfilechk
method and store it in a local variable rather than using a global anyway - that way you can use it for two different files in the future. In the case of a function defined to check if it was possible to open teh file, I''d return a bool
rather than a FILE* anyway - it makes your code a lot more readable.
这篇关于如何检查文件是否关闭? C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!