通过内存映射文件来颠倒文本内容(暂没有处理Unicode和换行符)

// ReverseFileDemo.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    if(!(argc >= 1))
    {
        cout<<"参数过少"<<endl;
        system("pause");
        return -1;
    }

    TCHAR szSrcFilePath[MAX_PATH]  = {0};
    _tcscpy_s(szSrcFilePath,argv[1]);
    wcout<<L"src file :"<<szSrcFilePath<<endl;

    HANDLE hFile = ::CreateFile(szSrcFilePath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if(hFile == INVALID_HANDLE_VALUE )
    {
        _tprintf_s(L"CreateFile error %d",::GetLastError());
        system("pause");
        return -1;
    }
    DWORD dwFileSize = ::GetFileSize(hFile,NULL);
    HANDLE hFileMap = ::CreateFileMapping(hFile,
        NULL,
        PAGE_READWRITE,
        0,
        dwFileSize + sizeof(WCHAR),
        NULL);
    if(hFileMap == NULL)
    {
        _tprintf_s(L"CreateFile error %d",::GetLastError());
        system("pause");
        return -1;
    }


    PVOID pvFile = MapViewOfFile(hFileMap,FILE_MAP_WRITE,0,0,0);
    int iUnicodeTestFlags = -1;
    BOOL bIsUnicode = ::IsTextUnicode(pvFile,dwFileSize,&iUnicodeTestFlags);
    if(!bIsUnicode)
    {
        PSTR pchAnsi = (PSTR) pvFile;
        pchAnsi[dwFileSize/(sizeof(CHAR))] = 0;
        _strrev(pchAnsi);
    }

    UnmapViewOfFile(pvFile);
    CloseHandle(hFileMap);
    SetFilePointer(hFile,dwFileSize,NULL,FILE_BEGIN);
    SetEndOfFile(hFile);
    CloseHandle(hFile);

    system("pause");
    return 0;
}

程序运行前文件内容为:1234567890

程序运行后文件内容为:0987654321

posted @ 2013-07-26 22:20  瓜蛋  阅读(475)  评论(0编辑  收藏  举报