用ifstream读UTF8格式文件的时候遇到了问题,求解

cwh63266178 2017-09-13 10:24:03
我要读一个xml文件,是utf8无BOM格式的
方法是先ifstream打开文件用seekg,tellg获得长度
然后构建了一个std::vector<char>,resize到文件长度+1
然后用ifstream的read读取到vector里


我原本文本最后一行是</datasources>
现在在读取的时候发现有问题,就是每有一个换行会多一个char的长度出来
我看了下读到的vector内容,发现换行位置没有\r只有\n,认为是这个影响长度的判断了
而且读出来的vector虽然最后多点长度出来,但是都是\0,
就是类似“...</datasources>\0\0\0\0\0\0\0”,不影响我后续对文本的处理所以也没在意


但是后来随着我更改了读取的文件内容后,发现读取开始有问题了
就是当文本的行数到一定数量后,原本会是\0的部分读取出了重复数据
,结果行数到七八行后,多出来的char长度不是\0了
结尾变成了"...</datasources>asources>\0"
等于多出的长度读出了重复的数据,随着长度加长继续往前读到换行位置还读出了\r
结果我在后续处理文本的时候就报错了
而且比较奇怪的是我在VS2015上编辑的同样代码读换行较多的文件最后也还是\0结尾的
但是我这次下的是QT的MingW版本,就出现了这个问题


有没有大佬知道这是什么问题,应该怎么处理?麻烦告诉下吧,谢谢了。
...全文
473 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2017-09-13
  • 打赏
  • 举报
回复
乍看起来c++的cin、cout、ifstream、ofstream、istringstream、ostringstream在输入、输出上比c的scanf、printf、fscanf、fprintf、fread、fwrite、sscanf、sprintf简单,不用格式控制符! 但是不用格式控制符,输入输出恰好是你期望的格式的时候好说;等到输入输出不是你期望的格式的时候,你就会觉得还是用格式控制符更方便、更靠谱。 摒弃cin、cout、ifstream、ofstream、istringstream、ostringstream! 使用scanf、printf、fscanf、fprintf、fread、fwrite、sscanf、sprintf。 In Visual C++ 2005, fopen supports Unicode file streams. A flag specifying the desired encoding may be passed to fopen when opening a new file or overwriting an existing file, like this: fopen("newfile.txt", "rw, ccs=<encoding>"); Allowed values of the encoding include UNICODE, UTF-8, and UTF16-LE. If the file is already in existence and is opened for reading or appending, the Byte Order Mark (BOM) is used to determine the correct encoding. It is not necessary to specify the encoding with a flag. In fact, the flag will be ignored if it conflicts with the type of the file as indicated by the BOM. The flag is only used when no BOM is present or if the file is a new file. The following table summarizes the modes used in for various flags given to fopen and Byte Order Marks used in the file. Flag No BOM (or new file) BOM: UTF-8 BOM: UTF-16 UNICODE ANSI UTF-8 UTF-16LE UTF-8 UTF-8 UTF-8 UTF-16LE UTF-16LE UTF-16LE UTF-8 UTF-16LE
cwh63266178 2017-09-13
  • 打赏
  • 举报
回复
找到了临时解决的办法,用二进制格式打开文本的话,读取出来的vector会带\r 这样长度就不会过长导致有多余的字符了,可是还是比较疑惑为啥用文本格式读会出现重复的数据 如果这是我没有正确使用ifstream导致的 那ifstream自己的应对这种问题的方法有没有比较权威的处理方法?
cwh63266178 2017-09-13
  • 打赏
  • 举报
回复
找到了这个问题相关的解释,贴在上面了。
cwh63266178 2017-09-13
  • 打赏
  • 举报
回复
https://stackoverflow.com/questions/27055771/using-seekg-in-text-mode

64,665

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧