c++ - Using Ubuntu gedit to write to a file -


i trying write simple program writes file exists. getting error:

hello2.txt: file not recognized: file truncated
collect2: ld returned 1 exit status

what doing wrong? (i tried slashes both ways , still same error.)

#include<iostream> #include<fstream> using namespace std;  int main() {     ofstream outstream;     outstream.open(hello3.txt);     outstream<<"testing";     outstream.close;      return 0; } 

there 2 errors in it:

  1. hello3.txt string , should therefore in quotes.

  2. std::ofstream::close() function, , therefore needs parenthesis.

the corrected code looks this:

#include <iostream> #include <fstream>  int main() {     using namespace std; // doing globally considered bad practice.         // in function (=> locally) fine though.      ofstream outstream;     outstream.open("hello3.txt");     // alternative: ofstream outstream("hello3.txt");      outstream << "testing";     outstream.close(); // not necessary, file         // closed when outstream goes out of scope , therefore destructed.      return 0; } 

and beware: code overwrites in file.


Comments