【问题标题】:C++ Ifstream reads too much?C++ Ifstream 读取太多?
【发布时间】:2011-10-26 07:49:59
【问题描述】:

我正在尝试读取文件并输出内容。一切正常,我可以看到内容,但最后似乎添加了大约 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;

【问题讨论】:

    标签: c++ html file char ifstream


    【解决方案1】:

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

    如果你想读取整个文件,这会容易得多:

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

    【讨论】:

    • +1。 IIRC 的搜索技巧在告诉您文件大小时甚至都不是那么可靠,尤其是在您以文本模式打开文件时。
    【解决方案2】:

    那是因为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 字符数之后停止打印。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      相关资源
      最近更新 更多