开发者

Using fopen twice on the same file with different access flags

I'm cleaning up some pretty complicated code that I didn't write and I'm looking for a way to touch the code as little as possible, so don't flame me for what may appear to be a newb question:

I have a library that works with an external data file that can be written to or read from, but generally all the writes happen at once and all the reads. Internally, the FILE* is fopened with "r+b", and the code appears to properly call fflush between switching between reads and writes. When the data file is in a place where the us开发者_运维知识库er has RW permissions, it works just as expected, however there are times where the data file may be in a location where the user has read-only permissions. Because of this the fopen(..."r+b") fails and returns a NULL file pointer and bad things are happening. It's totally reasonable for someone to have this data file in a read-only partition, they're not required to update the file and should be able to use the file in a read-only situation.

My question is instead of doing

FILE* pFile=fopen("filename","r+b");

could I edit the code and do something like

FILE* pRead=fopen("filename","rb");
FILE* pWrite=fopen("filename","r+b");

Then in the code that reads from the file, just use pRead, and in the code that writes to the file use pWrite. This way I could do something like this

int UpdateTheFile()
{
   if (!pWrite) return 0; //we know that we shouldn't even try to write
   //change all the existing update code to use pWrite instead of pFile
   return 1;
}

int ReadFromTheFile()
{
   if (!pRead) return 0;
   ...
   return 1;
}

It seems wrong to me to have two file pointers to the same file, but since the code is already "correct" in its ability to flush between reads and writes now, I'm guessing that things may be kept in sync. Also, it's guaranteed that only 1 thread will be accessing this file at a time, so I don't need to worry about concurrency issues here.

Is this a really bad idea and should I think about properly switching between read-only and read-write in the proper functions with an fclose/fopen pair, or can I get away with this as a "quick fix"


int file_is_writable = 1;
FILE *pFile = fopen("filename", "r+b");
if (!pFile) {
  pFile = fopen("filename", "rb");
  file_is_writable = 0;
  /* I highly suggest you check for open failure here and do something sane */
}

Then check file_is_writable before updates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜