文件的读写操作

1、文本文件的内容为:23+3=
要求:读入文本文件中的表达式,并计算表达式的值,写入到文本文件中,让文本文件的内容为:23+3=26
2、先靠自己的努力,查找资料,想办法将字符串:wchar_t szbuf[] = _T("我是VC驿站的粉丝!"); 写入到txt文件中,用系统默认的记事本打开之后能看到明文,不是乱码;
如果自己实在找不到办法,请参考:读写Unicode编码文件乱码解决方案:https://www.cctry.com/thread-298343-1-1.html

#include <Windows.h>
#include <tchar.h>
#include <iostream>    
#include <string>
#include <sstream>
using namespace std;
BOOL Read_File_Result(LPCTSTR lpFilePath)
{
    HANDLE hFile = CreateFile(lpFilePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
    if (hFile == INVALID_HANDLE_VALUE) return -1;
    char temp[100] = {0};
    DWORD Real_Read = 0;
    ReadFile(hFile, temp,sizeof(temp), &Real_Read,NULL);
    int a = 0;
    int t = 0;
    int b[100] = {0};
    int c = 0;
    for (;temp[t]!= 0;)
    {
        if (temp[t] >= '0' && temp[t] <= '9')
        {
            a = a * 10 + temp[t] - 48;
            if (!(temp[t+1] >= '0' && temp[t+1] <= '9'))
            {
                b[c++] = a;
                a = 0;
            }
        }
        temp[t++];
    }
    t = 0;
    int sum = {0};
    for (; b[t] != 0;)
    {
        sum = sum + b[t];
        b[t++];
    }
    char res[100] = { 0 };
    stringstream ss;         
    ss << sum;  
    ss >> res;
    strcat_s(temp,res);
    DWORD Real_Write = 0;
    CloseHandle(hFile);
    hFile = CreateFile(lpFilePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) return -1;
    BOOL bRet = WriteFile(hFile, temp, sizeof(temp), &Real_Write, NULL);
    if (bRet == FALSE) return FALSE;
    CloseHandle(hFile);
    return TRUE;
} 
BOOL Write_To_Txt(LPCTSTR lpFilePath)
{
    
    HANDLE hFile = CreateFile(lpFilePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) return -1;
    DWORD Real_Write = 0;
    BYTE unicodeHead[] = {0xFF, 0xFE};
    BOOL bRet = WriteFile(hFile, unicodeHead, sizeof(unicodeHead), &Real_Write, NULL);
    wchar_t szbuf[] = _T("我是VC驿站的粉丝!");
    bRet = WriteFile(hFile, szbuf, sizeof(szbuf), &Real_Write, NULL);
    if (bRet == FALSE) return FALSE;
    CloseHandle(hFile);
    return TRUE;
}
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, INT nCmdShow)
{
    BOOL bRet = Read_File_Result(_T("D:\\1.txt"));
    //BOOL bRet = Write_To_Txt(_T("D:\\2.txt"));
    return 0;
}

 

posted on 2021-01-20 20:39  SakuraQAQ  阅读(286)  评论(0)    收藏  举报

导航