Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect a file is opened or not in c

Tags:

c

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

like image 399
Peng Ren Avatar asked Feb 04 '13 04:02

Peng Ren


People also ask

What opens file in C?

The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc.

How do you know fopen failed?

You can do some error checking to see if the calls to fopen and fprintf succeeded. 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. Similarly fprintf return a negative number on error.

Why would a file fail to open in C?

The fopen() function will fail if: [EACCES] Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created.


1 Answers

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

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.

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

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

Failed: Permission denied
like image 194
Santosh Avatar answered Sep 19 '22 12:09

Santosh