c++ txt文件的读写及乱码问题解决

在编程中,我们经常需要对txt文件进行读写操作,有时候由于编解码问题,txt读写会出现乱码问题。下面介绍一种基于ofstream和ifstream的txt文件读写方法,并介绍txt文件读写的乱码解决方案。

1.txt文件写入

#include <fstream>
#include <iostream>
using namespace std;

int main()
{   
    ofstream outfile("1.txt",ios::ate);   //打开文件,设置写入方式为覆盖写入

    if(!outfile)
    {
        cout<<"txt文件打开失败!"<<endl;
        exit(0);
    }

    outfile<<"写入txt文件示例.\n";
    outfile<<"成功写入.\n";

    outfile.close();
}

txt里面的写入内容如下:
这里写图片描述

成功写入。

2.txt文件读出

对上面读入内容的txt进行读出操作,代码如下:

#include <fstream>
#include <iostream>
using namespace std;

int main()
{   
    char txt[100];
    ifstream infile;
    infile.open("1.txt");

    if(!infile.is_open())
    {
        cout<<"txt文件打开失败"<<endl;
        exit(0);
    }

    while(!infile.eof())
    {       
        infile.getline(txt,100);
        cout<<txt<<endl;
    }

    infile.close();
    getchar();
}

读出结果为:
这里写图片描述
读出结果正确。

3.txt读写乱码问题

有时候由于txt文件编码问题的不同,会导致读写的时候出现乱码,通常的txt编码方式有:
这里写图片描述
上面默认的编码方式为ANSI,如果我们现在将它另存为1.txt,但编码格式变为UTF-8,那么读出结果会变成:
这里写图片描述
发现结果完全错误,这时候我们需要编解码转换,具体代码如下:

#include <fstream>
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;

string UTF8ToGB(const char* str)
{
     string result;
     WCHAR *strSrc;
     LPSTR szRes;

     //获得临时变量的大小
     int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
     strSrc = new WCHAR[i+1];
     MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);

     //获得临时变量的大小
     i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
     szRes = new CHAR[i+1];
     WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);

     result = szRes;
     delete []strSrc;
     delete []szRes;

     return result;
}

int main()
{   
    char txt[100];
    string msg;
    ifstream infile;
    infile.open("2.txt");

    if(!infile.is_open())
    {
        cout<<""<<endl;
        exit(0);
    }

    while(!infile.eof())
    {       
        infile.getline(txt,100);
        msg=UTF8ToGB(txt);
        cout<<msg<<endl;

    }

    infile.close();
    getchar();
}

将读出结果进行上述转换,发现结果又正确了。

  • 43
    点赞
  • 163
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值