Reputation: 2179
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.
Upvotes: 4
Views: 1640
Reputation: 8286
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;
}
}
Upvotes: 3