Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must the file exist when using the 'r+' mode in fopen?

Tags:

c++

c

fopen

Why add this constraint when your intentions are to both read and write data to the file?

My application wants to open the file in both reading an writing mode. If I use w+ it will destroy the previous contests of the file, but at the same time it will create the file if it doesn't exist.

However if I use the r+ mode, my application will work properly, but if the file doesn't exist it will throw an exception about the nonexistence of the file.

like image 731
jsguy Avatar asked Sep 01 '25 22:09

jsguy


1 Answers

Try something like this. If the first fopen fails because the file does not exist, the second fopen will try to create it. If the second fopen fails there are serious problems.

if((fp = fopen("filename","r+")) == NULL) {
    if((fp = fopen("filename","w+")) == NULL) {
        return 1;
    }
}
like image 55
user3121023 Avatar answered Sep 03 '25 11:09

user3121023