how to detect a file is opened or not in c

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

Leave a Comment