[英]Binary File Input,Output and Append C++
我正在 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”和一些额外字符。
你能帮我找出问题所在吗?
提前致谢
问题似乎不在于写入文件,而在于读取和显示它,即这里:
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;
我认为您的错误在 output 上:
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout<< memblock<<endl;
cout << memblock << endl
是否知道将确切size
的字节写入 output stream? 还是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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.