C语言 c - 如何检测文件是否在c中打开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14680232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:14:11  来源:igfitidea点击:

how to detect a file is opened or not in c

c

提问by Peng Ren

I'm trying to output some string on a txt file by using c program

我正在尝试使用 c 程序在 txt 文件上输出一些字符串

however, I need to see if the I have the permission to write on the txt file, if not, I need to print out the error message? However, I don't know how to detect if I successfully open a file or not, could someone help me about this? thanks

但是,我需要看看我是否有权限在txt文件上写入,如果没有,我需要打印出错误信息吗?但是,我不知道如何检测我是否成功打开文件,有人可以帮助我吗?谢谢

The code is like this

代码是这样的

File *file = fopen("text.txt", "a");

fprintf(file, "Successfully wrote to the file.");

//TO DO (Which I don't know how to do this)
//If dont have write permission to text.txt, i.e. open was failed
//print an error message and the numeric error number

Thank you for anyone helps, thanks a lot

感谢任何人的帮助,非常感谢

回答by Santosh

You need to check the return value of fopen. From the man page:

您需要检查 fopen 的返回值。从手册页:

RETURN VALUE
   Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer.
   Otherwise, NULL is returned and errno is set to indicate the error.

To check whether write is sucessful or not again, check the return value of fprintf or fwrite. To print what is the reason for the failure you can check errno, or use perror to print the error.

要再次检查写入是否成功,请检查 fprintf 或 fwrite 的返回值。要打印失败的原因,您可以检查 errno,或使用 perror 打印错误。

f = fopen("text", "rw");
if (f == NULL) {
    perror("Failed: ");
    return 1;
}

perror will print the error like the following (in case of no permission):

perror 将打印如下错误(在没有权限的情况下):

Failed: Permission denied

回答by Bharat

You can do some error checking to see if the calls to fopen and fprintf succeeded.

您可以进行一些错误检查以查看对 fopen 和 fprintf 的调用是否成功。

fopen's return value is the pointer to the file object on success and a NULL pointer on failure. You could check for NULL return value.

fopen 的返回值是成功时指向文件对象的指针,失败时返回 NULL 指针。您可以检查 NULL 返回值。

FILE *file = fopen("text.txt", "a");

if (file == NULL) {
     perror("Error opening file: ");
}

Similarly fprintf return a negative number on error. You could do a if(fprintf() < 1)check.

同样, fprintf 在出错时返回负数。你可以做个if(fprintf() < 1)检查。

回答by William Pursell

f = fopen( path, mode );
if( f == NULL ) {
  perror( path );
}