Ifstream 在几行后停止读取文件 [英] Ifstream stops reading file after a few lines

查看:31
本文介绍了Ifstream 在几行后停止读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ifstreamstringstream 来读取文件,但它在几行后停止...

I am using an ifstream into a stringstream for reading a file but it stops after a couple lines...

string read(string filename)
{
    ifstream inFile;
    inFile.open(filename);
    stringstream strStream;
    strStream << inFile.rdbuf();
    inFile.close();
    string str = strStream.str();
    return str;
}

这段代码在'zh¬'之后停止
我想也许它们是 ascii 表中的控制字符,停止后的第一个字符是 26.
但我认为这不重要.

This code stops after 'zh¬'
I am thinking maybe they are control characters in the ascii table, the first char after it stops is 26.
But i wouldn't think that matters.

推荐答案

您的 ifstream 正在以文本模式打开.尝试以二进制模式打开文件:std::ifstream inFile(filename, std::ios::binary);

Your ifstream is being opened in text mode. Try opening the file in binary mode: std::ifstream inFile(filename, std::ios::binary);

文本流是由行组成的有序字符序列(零个或多个字符加上终止的\n").最后一行是否需要终止 '\n' 是实现定义的.可能必须在输入和输出中添加、更改或删除字符以符合操作系统中表示文本的约定(特别是,Windows 操作系统上的 C 流在输出时将 \n 转换为 \r\n,并将 \r\n 到 \n 输入)

A text stream is an ordered sequence of characters composed into lines (zero or more characters plus a terminating '\n'). Whether the last line requires a terminating '\n' is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert \n to \r\n on output, and convert \r\n to \n on input)

  • 只有在以下所有条件都为真时,才能保证从文本流中读入的数据与之前写出到该流中的数据相比较:
    数据仅由打印字符和控制字符\t 和\n 组成(特别是在Windows 操作系统上,字符'\0x1A' 终止输入)

  • Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if all of the following is true:
    the data consist only of printing characters and the control characters \t and \n (in particular, on Windows OS, the character '\0x1A' terminates input)

no \n 前紧跟一个空格字符(在 \n 之前写出的空格字符在读取时可能会消失)

no \n is immediately preceded by a space character (space characters that are written out immediately before a \n may disappear when read)

最后一个字符是\n

二进制流是一个有序的字符序列,可以透明地记录内部数据.从二进制流中读入的数据总是等于早先写出到该流中的数据.实现只允许在流的末尾附加一些空字符.宽二进制流不需要以初始移位状态结束.

A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equals to the data that were earlier written out to that stream. Implementations are only allowed to append a number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state.

https://en.cppreference.com/w/cpp/io/c#Binary_and_text_modes

这篇关于Ifstream 在几行后停止读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆