how to detect a file is opened or not in c

前端 未结 3 1032
天命终不由人
天命终不由人 2020-12-03 15:04

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 pr

相关标签:
3条回答
  • 2020-12-03 15:21
    f = fopen( path, mode );
    if( f == NULL ) {
      perror( path );
    }
    
    0 讨论(0)
  • 2020-12-03 15:26

    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.

    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.

    0 讨论(0)
  • 2020-12-03 15:28

    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
    
    0 讨论(0)
提交回复
热议问题