二进制文件输入、输出和附加C++
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"和一些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;
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词