zoukankan      html  css  js  c++  java
  • C++ File on Windows

    Create file

    HANDLE hFile = ::CreateFile(lpcszFileName, GENERIC_READ | GENERIC_WRITE,  
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
     
    Create file with specified size
    BOOL bResult = FALSE; 
    HANDLE hFile = ::CreateFile(lpcszFileName, GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE == hFile)
    {
    return (BOOL)::GetLastError();
    }

    HANDLE hFileMap = ::CreateFileMapping(hFile, NULL, PAGE_READWRITE, dwHigh, dwLow, NULL);
    if (NULL == hFileMap)
    {
    return (BOOL)::GetLastError();
    }

    ::CloseHandle(hFileMap);
    ::CloseHandle(hFile);

    WriteFile is more efficient than fwrite, because fwrite calls down to WriteFile internally

    #include <Windows.h>
    #include <stdio.h>
    #include <iostream>

    int main() {
    FILE* cfile = fopen("file1.txt", "w");
    HANDLE wfile = CreateFile("file2.txt", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS,
    /*FILE_ATTRIBUTE_NORMAL*/FILE_FLAG_WRITE_THROUGH, NULL);
    DWORD written = 0;

    DWORD start_time, end_time;
    char * text = "test message ha ha ha ha";
    int size = strlen(text);
    int times = 999;

    start_time = timeGetTime();
    for(int i = 0; i < times; ++i) {
    fwrite(text, 1, size, cfile);
    fflush(cfile);
    }
    end_time = timeGetTime();
    std::cout << end_time - start_time << '\n';

    start_time = timeGetTime();
    for(int i = 0; i < times; ++i) {
    WriteFile(wfile, text, size, &written, NULL);
    //FlushFileBuffers(wfile);
    }
    end_time = timeGetTime();
    std::cout << end_time - start_time << std::endl;

    system("pause");
    return 0;
    }
    Do not call FlushFileBuffers explicitly, data in system cache will be flushed to disk when needed.
    Get a buffer for WriteFile, just as fwrite does, because API call cost more time than simply memcpy, call WriteFile when buffer is filled up.
    For windows, fwrite() will write the data to a buffer until that buffer fills, which will cause it to send the data in the buffer to WriteFile() call. When you call fflush() all that happens is that the data currently in the buffer is passed to a call to WriteFile() – fflush() doesn't call FlushFileBuffer().
     
    Rename a file
    if (MoveFile(_T("c:\\temp\\down.txt.tg"), _T("c:\\temp\\down.txt")) == 0)
    {
    cout<<::GetLastError()<<endl;
    }


  • 相关阅读:
    length()
    matlab mod()&rem()
    tf调试函数
    64位win7+PCL1.6.0+VS2010,64位win10+PCL1.6.0+VS2010
    pcl 1.8 + VS 2010 在win7 x64下的配置
    Qt在vs2010下的配置
    VS2010 win7 QT4.8.0,实现VS2010编译调试Qt程序,QtCreator静态发布程序
    [POI2012]ROZ-Fibonacci Representation (贪心)
    CF 666C & 牛客 36D
    数位dp练习
  • 原文地址:https://www.cnblogs.com/rogerroddick/p/2944006.html
Copyright © 2011-2022 走看看