二进制文件输入、输出和追加 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”和一些外部字符。
你能帮我找出问题所在吗?
提前致谢
I'm trying a basic input,output(and append) in C++ here is my code
#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;
}
}
It runs well the first time, but when I run it a second time it adds "hello" and some extrange characters to the file.
Could you please help me figure out what's wrong?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题似乎不在于写入文件,而是在于显示文件,即此处:
使用cout显示预计字符串以空结尾。但是您只为文件内容分配了足够的空间,而不是终止符。添加以下内容应该可以使其工作:
The problem doesn't seem to be with writing the file but rather with reading and displaying it, namely here:
Displaying with cout expects the string to be null terminated. But you only allocated enough space for the file contents and not the terminator. Adding the following should make it work:
我认为你的错误出现在输出上:
Does
cout <<内存块<< endl
知道将准确size
字节写入输出流吗?或者char foo[]
是否被视为 C 风格字符串,_which 必须以 asciiNUL
终止?如果必须以 ASCII
NUL
终止,请尝试以下操作:I think your errors are on output:
Does
cout << memblock << endl
know to write exactlysize
bytes to the output stream? Or is thechar foo[]
taken to be a C-style string, _which must be terminated with an asciiNUL
?If it must be terminated with an ASCII
NUL
, try this: