二进制文件输入,输出和附加C++

Mar*_*les 2 c++ input append stream

我在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它第一次运行良好,但是当我第二次运行它时,它会向文件中添加"hello"和一些外部字符.

你能帮我弄清楚出了什么问题吗?

提前致谢

Pab*_*blo 5

问题似乎不是文件而是阅读和显示它,即:

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

使用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;
Run Code Online (Sandbox Code Playgroud)