如何检查文件是否关闭? C [英] how to check a file is close ? c

查看:89
本文介绍了如何检查文件是否关闭? C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;

推荐答案

openfilechk 函数不会更改fp以指示关闭状态。因此,如果它成功打开,它总是会指示您打开的文件块。

You openfilechk function does not change fp to indicate the closed status. As a result, if it opened sucessfully, it always leaves it indicating the file block you opened.
#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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆