http://shushanyegui.duapp.com/?p=731

在描述内存映射文件之前 我们先来写一个系统通过I/O来读写磁盘文件的小程序

#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>

char* Read(LPCWSTR file)
{
    HANDLE hFile = CreateFile(
        (LPCWSTR)file,
        GENERIC_READ,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL
        );
    DWORD filesize = GetFileSize(hFile, NULL);
    int size = filesize + 1;
    char *buff = (char *)malloc(sizeof(char)*size);
    for (int i = 0; i<size; i++)
    {
        buff[i] = 0;
    }
    DWORD readBytes;
    BOOL flag = ReadFile(hFile, buff, size, &readBytes, NULL);
    if (flag == FALSE)
    {
        printf("ReadFile failed/n");
        return "false";
    }
    CloseHandle(hFile);
    return buff;

}

BOOL Write(LPCWSTR file, char *con)
{
    HANDLE hFile = CreateFile(
        (LPCWSTR)file,
        GENERIC_WRITE | GENERIC_READ,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL
        );
    if (hFile == INVALID_HANDLE_VALUE)
    {
        return false;
    }
    //TCHAR buff[MAX_PATH];
    DWORD wSize;
    char buff[MAX_PATH];
    sprintf_s(buff, "%s", con);
    BOOL flag = WriteFile(hFile, buff, strlen(buff), &wSize, NULL);
    if (!flag){
        return false;
    }
    //缓冲区内容强制刷新至设备
    if (0 == FlushFileBuffers(hFile))
    {
        printf("Flush failed/n");
    }
    CloseHandle(hFile);
    return true;

}
void TcharToChar(const TCHAR * tchar, char * _char)
{
    int iLength;
    //获取字节长度   
    iLength = WideCharToMultiByte(CP_ACP, 0, tchar, -1, NULL, 0, NULL, NULL);
    //将tchar值赋给_char    
    WideCharToMultiByte(CP_ACP, 0, tchar, -1, _char, iLength, NULL, NULL);
}

void CharToTchar(const char * _char, TCHAR * tchar)
{
    int iLength;
    iLength = MultiByteToWideChar(CP_ACP, 0, _char, strlen(_char) + 1, NULL, 0);
    MultiByteToWideChar(CP_ACP, 0, _char, strlen(_char) + 1, tchar, iLength);
}

int main(int argc, char **argv){
    LPCWSTR filename = TEXT("test.txt");
    char *con = "Hey guys!!";
    if (Write(filename, con))
    {
        MessageBox(NULL, TEXT("Write success!!!"), TEXT("OK"), MB_OK);
    }

    char *buff = Read(filename);
    TCHAR str[256];

    CharToTchar(buff, str);

    if (str)
    {
        TCHAR readBuff[MAX_PATH];
        wsprintf(readBuff, TEXT("%s"), str);
        OutputDebugString(readBuff);
        MessageBox(NULL, readBuff, TEXT("OK"), MB_OK);
    }
    else {
        MessageBox(NULL, TEXT("Oops! There happends something!!"), TEXT("ERROR"), MB_OK);
    }
    return 0;
}
View Code

相关文章:

  • 2022-12-23
  • 2021-07-15
猜你喜欢
  • 2022-12-23
  • 2021-10-10
  • 2021-05-21
相关资源
相似解决方案