I hope this helps. walk through it with a debugger and see what happens when you run the program the second time.
Code:
#include <iostream>
#include <fstream>
char MY_STRING[] = "Lets talk about files[:>)\n";
void error(){std::cout << "Something bad happened";system("pause"); exit(1);}
const unsigned int data_buffer_size = 30;
int main()
{
char data[ data_buffer_size ]; //data buffer
std::cout << MY_STRING;
system("pause");
std::cout << "Lets make a file\n";
std::fstream FILE;
//I'm using fstream because it is both an input and output stream.
//You can read and write to the same file. but lets keep it simple.
//Different ways to open a file.
//std::ios:: ... unsigned int type
// app, append
// ate, open and seek to the end of file
// binary, I/O to be done in binary mode
// in, Open for read only access
// out, open for write access
// trunc, truncate file to 0 - length
/////////////////////////////////////////////////
FILE.open("FILENAME", std::ios::out | std::ios::app);
//Default includes std::ios::text.
if(FILE.is_open()){
//My File has been opened. Lets do something with it.
FILE << MY_STRING << std::endl;
//is ALMOST the same as
FILE.write(MY_STRING, strlen(MY_STRING));
//Error check
if(FILE.bad())
error();
//So everything went well.
FILE.close();
}else{
error();
}
//Now lets read from the file.
FILE.open("FILENAME", std::ios::in);
if(FILE.is_open()){
for( int LINE_NUMBER = 0; !FILE.eof(); LINE_NUMBER++){
//This reads 1 line from the file to the buffer.
FILE.getline(&data[0], data_buffer_size);
std::cout << LINE_NUMBER << ": " << data << std::endl;
}
FILE.close();
}
system("pause");
return 0;
}
also try changing 'MY_STRING' to more than 30 chars and see what happens.