Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

how to detect a file is opened or not in 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...