开发者

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>
#incl开发者_如何学运维ude<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜