c++ txt文件的读写及乱码问题解决
来源:互联网 发布:windows 2008 dhcp 编辑:程序博客网 时间:2024/06/04 19:24
在编程中,我们经常需要对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();}
将读出结果进行上述转换,发现结果又正确了。
1 0
- c++ txt文件的读写及乱码问题解决
- 【c#】读写txt文件
- [C#]解决读写包含汉字的txt文件时乱码的问题
- [C#]解决读写包含汉字的txt文件时乱码的问题
- 转:[C#]解决读写包含汉字的txt文件时乱码的问题
- [C#]解决读写包含汉字的txt文件时乱码的问题
- [C#]解决读写包含汉字的txt文件时乱码的问题
- [C#]解决读写包含汉字的txt文件时乱码的问题
- C-语言TXT文件的读写
- Java读写txt文件中文乱码问题的解决
- Java读写json格式的txt文件中文乱码问题
- 【C#】txt的读写
- C语言读写txt文件
- C语言读写txt文件
- c读写txt文件示例
- gedit打开txt文件乱码问题解决
- Java读写txt文件中文乱码问题
- java读写txt文件中文乱码问题
- 在CentOS安装CMake (CentOS7 64位适用)
- HTTP协议详解
- LEETCODE--Summary Ranges
- 设计模式--有道笔记的整理
- SVM总结及SMO简单实现
- c++ txt文件的读写及乱码问题解决
- 奇葩问题:ListView中Item与Item中的Button不能单击问题
- ImageView根据图片横竖自适应调整宽高
- ButterKnife基本使用
- 在录入数据时可能会遇到的问题--有道笔记的整理
- 欢迎使用CSDN-markdown编辑器
- gradle的使用,依赖管理
- android 修改system\build.prop
- android 中OnKeyDown的事件获取顺序