开发者

Can a failed fopen impact the filesystem?

If fopen( path, "w" ) succeeds, then the file will be truncated. If the fopen fails, are there an guarantees that the file is not modified?开发者_开发百科


No there are no guarantees about the state of a file if fopen(path, "w") fails. The failure could be coming from any operation from opening the file, committing the truncation to disk, etc ... The only guarantee a failure provides is that you don't have access to the file.


The only reason why fopen() would fail would be if the file is somehow inaccessible or cannot be modified. If you are worried, though, about the file being modified, you could instead use the open() command with the flag O_WRITE. You could then convert this to a FILE* pointer by using fdopen().


Excellent question, and I think the answer is no. fopen has to allocate a FILE structure, and the natural order of operations when implementing it would be to open the file first, then attempt allocating the FILE. This way, fopen is just a wrapper around fdopen (or a similar function with some leading underscores or whatnot for namespace conformance).

Personally I would not use stdio functions at all when you care about the state of your files after any failure. Even once you have the file open, stdio's buffering makes it almost impossible to know where an error occurred if a write function ever returns failure, and even more impossible to return your file to a usable, consistent state.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜