使用 Ubuntu gedit 写入文件

发布于 2024-11-04 01:55:46 字数 429 浏览 1 评论 0原文

我正在尝试编写一个简单的程序来写入已存在的文件。我收到此错误:

hello2.txt:无法识别文件:文件被截断
collect2:ld返回1退出状态

我做错了什么? (我尝试了两种斜杠,但仍然遇到相同的错误。)

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    ofstream outStream;
    outStream.open(hello3.txt);
    outStream<<"testing";
    outStream.close;

    return 0;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笨死的猪 2024-11-11 01:55:46

其中有两个错误:

  1. hello3.txt 是一个字符串,因此应该用引号引起来。

  2. std::ofstream::close() 是一个函数,因此需要括号。

更正后的代码如下所示:

#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;
}

请注意:此代码会覆盖该文件中先前存在的任何内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文