【问题标题】:Reading fstream returns junk读取 fstream 返回垃圾
【发布时间】:2012-12-11 05:13:15
【问题描述】:

我正在尝试读取仅包含字符串的文本文件。它正在编译和打开,但在读取时只显示与文件中的字符完全无关的垃圾。

谁能看出问题所在?

#include <iostream>
#include <fstream>

using namespace std;

fstream myfile;
char* input;

void main(void)
{
    myfile.open("H://fstream_test.txt", fstream::in);
    if(myfile.fail()) 
    {
        cout<<"error"; exit(0);
    }
    cout<<"file is open";

    int beginning = myfile.tellg();
    myfile.seekg(0, fstream::end);
    int end = myfile.tellg();
    int size = end-beginning;
    cout<<size; //returns 15

    input = new char[size];
    myfile.read(input,size);

    cout<<input;
    //returns junk

    //for(int i=0;i<size;i++)
        //cout<<input[i];
    //returns the same;
}

结束编辑为:

input = new char[size];
    myfile.seekg(0, fstream::beg);
    while(!myfile.eof())
    {
        myfile.read(input,size);
    }

    cout<<input;
    system("pause");

【问题讨论】:

  • 输入=新字符[大小];没有删除[]。那是内存泄漏。请改用标准库容器。

标签: c++


【解决方案1】:

在尝试阅读之前,您先搜索到文件末尾:

myfile.seekg(0, fstream::end);

要完成这项工作,您必须先从头开始。

另请注意,myfile.read() 不会附加 NUL 终止符。

【讨论】:

  • 它正在阅读文本,但之后仍然有很多垃圾。我试过包括一个 while !eof 循环,但没有奏效。我将在上面显示编辑后的代码。
  • @MatthewParker:没有 NUL 终止符。你必须自己添加它(确保你已经为它分配了空间)。或者,将文本放入std::string
  • 就像我必须将 NUL 终止符添加到文本文件“0”中一样。如果我将其保存为二进制文件,这会自动发生吗?
猜你喜欢
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
相关资源
最近更新 更多