How to detect file open or not in c

I am trying to output some line in a txt file using c program

however, I need to figure out if I have permission to write to the txt file, if not, I need to print the error message? However, I don't know how to determine if I opened the file successfully or not, can anyone help me? thank

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

      

Thanks for the help, thanks a lot

+3


source to share


3 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 if the write is successful or not, check the return value of fprintf or fwrite. To print out 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 throw an error like this (in the absence of permission):

Failed: Permission denied

      

+7


source


You can do some error checking to make sure the fopen and fprintf calls succeed.

The return value of fopen is a pointer to a successful file and a NULL pointer on error. You can check the return value for NULL.



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

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

      

Similarly, fprintf returns a negative number on error. You can check if(fprintf() < 1)

.

+4


source


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

      

+1


source







All Articles