I am trying to write a simple program that writes to a file that already exists. I am getting this error:
hello2.txt: file not recognized: File truncated
collect2: ld returned 1 exit status
What am I doing wrong? (I tried the slashes both ways and I still get the same error.)
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream outStream;
outStream.open(hello3.txt);
outStream<<"testing";
outStream.close;
return 0;
}
There are two errors in it:
hello3.txt is a string and should therefore be in quotes.
std::ofstream::close() is a function, and therefore needs parenthesis.
The corrected code looks like this:
#include <iostream>
#include <fstream>
int main()
{
using namespace std; // doing this globally is considered bad practice.
// in a function (=> locally) it is fine though.
ofstream outStream;
outStream.open("hello3.txt");
// alternative: ofstream outStream("hello3.txt");
outStream << "testing";
outStream.close(); // not really necessary, as the file will get
// closed when outStream goes out of scope and is therefore destructed.
return 0;
}
And beware: This code overwrites anything that was previously in that file.