huidong

首页 | 会员登录 | 关于争取 2022 寒假做出汇东网 Ver3.0.0 !
搜索文章



用起来比 fopen 方便。举个例子:

#include <string>
#include <fstream>
#include <streambuf>
using namespace std;

// 获取文件内容
string GetFile(const char* filepath)
{
    ifstream t(filepath);
    string str((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
    t.close();

    if (str.size() <= 0)
    {
        printf("\n\nopen %s error.", filepath);
        //_getch();
        exit(-1);
    }

    return str;
}


// 输出文件
ofstream out(path);
out.write(str.c_str(), str.size());
out.close();


实测可用。


关于 ifstream 和 ofstream 的更多用法……随便找了个文章:https://blog.csdn.net/weixin_42587961/article/details/86677869 


补充:

wifstream 读取中文乱码问题:

    std::wifstream file(TXT_PATH);
    file.imbue(std::locale("chs"));    // 用 chs 解决 ANSI 文件乱码,zh_CN.UTF-8 解决 UTF-8 文件。
    wstr.assign((std::istreambuf_iterator<wchar_t>(file)), std::istreambuf_iterator<wchar_t>());
    file.close();

// 读取文件
std::wstring ReadFile(const wchar_t* path)
{
    std::wifstream file(path);
    file.imbue(std::locale("chs"));
    std::wstring wstr((std::istreambuf_iterator<wchar_t>(file)), std::istreambuf_iterator<wchar_t>());
    file.close();
    return wstr;
}







返回首页


Copyright (C) 2018-2024 huidong