简体   繁体   中英

Using Ubuntu gedit to write to a file

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:

  1. hello3.txt is a string and should therefore be in quotes.

  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM