14

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

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

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

4

3 回答 3

20

您需要检查 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.

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

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

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

Failed: Permission denied
于 2013-02-04T04:14:32.830 回答
11

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

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

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

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

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

于 2013-02-04T04:18:07.303 回答
1
f = fopen( path, mode );
if( f == NULL ) {
  perror( path );
}
于 2013-02-04T04:15:03.223 回答