【问题标题】:Binary File Input,Output and Append C++二进制文件输入、输出和追加 C++
【发布时间】:2011-06-03 02:23:28
【问题描述】:

我正在尝试 C++ 中的基本输入、输出(和附加),这是我的代码

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;



void escribir(const char *);
void leer(const char *);

int main ()
{
    escribir("example.bin");
    leer("example.bin");
    system("pause");
    return 0;
}

void escribir(const char *archivo)
{
    ofstream file (archivo,ios::app|ios::binary|ios::ate);
    if (file.is_open())
    {
        file<<"hello";
        cout<<"ok"<<endl;
    }
    else
    {
        cout<<"no ok"<<endl;
    }
    file.close();


}

void leer(const char *archivo)
{
    ifstream::pos_type size;
    char * memblock;

    ifstream file (archivo,ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
        size = file.tellg();
        memblock = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();

        cout<< memblock<<endl;

        delete[] memblock;
    }
    else
    {
        cout << "no ok"<<endl;
    }
}

它第一次运行良好,但当我第二次运行它时,它会在文件中添加“hello”和一些额外字符。

你能帮我找出问题所在吗?

提前致谢

【问题讨论】:

  • 我无法重现这一点:我使用 VC10 得到的正是“hellohello”68 6f 6c 6c 6f 68 6f 6c 6c 6f。你能发布文件的十六进制内容吗?
  • 啊。没有看到滚动条。

标签: c++ input stream append


【解决方案1】:

问题似乎不在于写入文件,而在于读取和显示它,即这里:

memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout<< memblock<<endl;

使用 cout 显示期望字符串以空值结尾。但是您只为文件内容分配了足够的空间,而不是终止符。添加以下内容应该可以使其工作:

memblock = new char [size+1]; // add one more byte for the terminator
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
memblock[size] = 0;  // assign the null terminator
cout<< memblock<<endl;

【讨论】:

    【解决方案2】:

    我认为你的错误在输出:

        memblock = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();
    
        cout<< memblock<<endl;
    

    cout &lt;&lt; memblock &lt;&lt; endl 是否知道将 准确 size 字节写入输出流?还是 char foo[] 被视为 C 风格的字符串,_which 必须以 ascii NUL 结尾?

    如果它必须以 ASCII NUL 结束,试试这个:

        memblock = new char [size + 1];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();
        memblock[size]='\0';
    
        cout<< memblock<<endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 2010-12-01
      • 1970-01-01
      相关资源
      最近更新 更多