每隔几毫秒写一个文件最有效(最快)的方法是什么?

时间:2016-01-11 00:57:33

标签: c++ windows

我需要打开一个文件,每隔几毫秒写一个文件到一个文件,然后关闭文件。这样做最有效的方法是什么?目前,它正在导致高CPU利用率。

1 个答案:

答案 0 :(得分:0)

编写文件的最快方法是使用系统API。由于您使用的是Windows:https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534(v=vs.85).aspx

HANDLE hfile = CreateFile("file",              // name of the write
                       GENERIC_WRITE,          // open for writing
                       0,                      // do not share
                       NULL,                   // default security
                       CREATE_NEW,             // create new file only
                       FILE_ATTRIBUTE_NORMAL,  // normal file
                       NULL);                  // no attr. template
bErrorFlag = WriteFile( 
                    hfile,           // open file handle
                    DataBuffer,      // start of data to write
                    dwBytesToWrite,  // number of bytes to write
                    &dwBytesWritten, // number of bytes that were written
                    NULL);           // no overlapped structure

CloseHandle(hFile);

此外,在加载应用程序时打开文件,并在销毁应用程序时关闭文件,因为打开和关闭文件是缓慢的部分。也就是说,每次需要编写时都不要打开/关闭文件,而只需要编写一次。

这些功能位于<windows.h>