C++如果stream读取太多?

发布于 2024-11-29 22:46:22 字数 566 浏览 0 评论 0原文

我正在尝试读取文件并输出内容。一切正常,我可以看到内容,但似乎在末尾添加了大约 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饮惑 2024-12-06 22:46:22

您没有在 char 数组上放置空终止符。不是 ifstream 读取太多,cout 只是在没有空终止符的情况下不知道何时停止打印。

如果你想读取整个文件,这更容易:

std::ostringstream oss;
ifstream fin("index.html");
oss << fin.rdbuf();
std::string html = oss.str();
std::cout << html;

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:

std::ostringstream oss;
ifstream fin("index.html");
oss << fin.rdbuf();
std::string html = oss.str();
std::cout << html;
ぶ宁プ宁ぶ 2024-12-06 22:46:22

这是因为 html 不是以 null 结尾的字符串,并且 std::cout 会一直打印字符,直到找到 \0,否则可能会崩溃您的程序

执行此操作:

html = new char [length +1 ];

is.read(html, length);
html[length] = '\0'; // put null at the end
is.close();
cout << html;

或者,您可以执行此操作:

cout.write(html, length);

cout.write 将在 length 个字符后停止打印。

That is because html is not null-terminated string, and std::cout keeps printing character until it finds \0, or it may crash your program

Do this:

html = new char [length +1 ];

is.read(html, length);
html[length] = '\0'; // put null at the end
is.close();
cout << html;

Or, you can do this:

cout.write(html, length);

cout.write will stop printing exactly after length number of chars.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文