如何检查文件是否关闭? C

编程入门 行业动态 更新时间:2024-10-24 16:22:45
本文介绍了如何检查文件是否关闭? 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

本文发布于:2023-10-04 04:05:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467116.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!