C++如果stream读取太多?
我正在尝试读取文件并输出内容。一切正常,我可以看到内容,但似乎在末尾添加了大约 14 个空字节。有谁知道这段代码有什么问题吗?
int length;
char * html;
ifstream is;
is.open ("index.html");
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
html = new char [length];
is.read(html, length);
is.close();
cout << html;
delete[] html;
I'm trying to read a file and output the contents. Everything works fine, I can see the contents but it seems to add about 14 empty bytes at the end. Does anyone know whats wrong with this code?
int length;
char * html;
ifstream is;
is.open ("index.html");
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
html = new char [length];
is.read(html, length);
is.close();
cout << html;
delete[] html;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有在 char 数组上放置空终止符。不是 ifstream 读取太多,cout 只是在没有空终止符的情况下不知道何时停止打印。
如果你想读取整个文件,这更容易:
You didn't put a null terminator on your char array. It's not ifstream reading too much, cout just doesn't know when to stop printing without the null terminator.
If you want to read an entire file, this is much easier:
这是因为
html
不是以 null 结尾的字符串,并且std::cout
会一直打印字符,直到找到\0
,否则可能会崩溃您的程序执行此操作:
或者,您可以执行此操作:
cout.write
将在length
个字符后停止打印。That is because
html
is not null-terminated string, andstd::cout
keeps printing character until it finds\0
, or it may crash your programDo this:
Or, you can do this:
cout.write
will stop printing exactly afterlength
number of chars.