Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Windows, should I use CreateFile or fopen, portability aside?

What are the differences, and in what cases one or the other would prove superior in some way?

like image 450
CannibalSmith Avatar asked Jun 14 '10 14:06

CannibalSmith


1 Answers

First of all the function fopen can be used only for simple portable operations with files.

CreateFile on the other side can be used not only for operations with files, but also with directories (with use of corresponding options), pipes and various Windows devices.

CreateFile has a lot of additional useful switches, like FILE_FLAG_NO_BUFFERING, FILE_ATTRIBUTE_TEMPORARY and FILE_FLAG_SEQUENTIAL_SCAN, which can be very useful in different scenarios.

You can use CreateFile with a filename longer that MAX_PATH characters. It can be important for some server applications or ones which must be able to open any file (a virus scanner or a backup application for example). This is enabled by using namespace semantics, though this mode has its own concerns, like ability to actually create a file named ".." or L"\xfeff\x20\xd9ab" (good luck trying to delete them later).

You can use CreateFile in different security scenarios. I mean not only usage of security attributes. If current process has SE_BACKUP_NAME or SE_RESTORE_NAME privilege (like Administrators typically have) and enable this privilege, one can use CreateFile to open any file also a file to which you have no access through security descriptor.

If you only want to read the content of a file, you can use CreateFile, CreateFileMapping and MapViewOfFile to create file mapping. Then you can work with a file as with a block of memory, which can possibly increase your application's speed.

There are also other uses of the function, which are described in detail in the corresponding MSDN article.

So I can summarize: only if you have a hard portability requirements or if you need to pass a FILE* to some external library, then you have to use fopen. In all other cases I would recommend you to use CreateFile. For best results, I would also advise to learn Windows API specifically, as there are many features that you can find a good use for.

UPDATED: Not directly related to your question, but I also recommend you to take a glance at transactional I/O functions which are supported starting with Windows Vista. Using this feature, you can commit a bunch of operation with files, directories or registry as one transaction that cannot be interrupted. It is a very powerful and interesting tool. If you are not ready now to use the transactional I/O functions, you can start with CreateFile and port your application to transactional I/O later.

like image 130
Oleg Avatar answered Oct 09 '22 03:10

Oleg