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

Binary File Input,Output and Append C++

本文关键字:C++ 输出 输入 二进制文件      更新时间:2023-10-16

我正在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"和一些extrange字符。

你能帮我弄清楚怎么了吗?

提前感谢

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

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

使用cout进行显示时,字符串应以null结尾。但是您只为文件内容分配了足够的空间,而没有为终止符分配足够的空间。添加以下内容将使其发挥作用:

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;

我认为您的错误在输出上:

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

cout << memblock << endl是否知道将精确地size字节写入输出流?或者char foo[]是一个C风格的字符串,_w必须以ascii NUL结尾?

如果必须使用ASCII NUL终止,请尝试以下操作:

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