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
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: