【问题标题】:Writing On Text File C++编写文本文件 C++
【发布时间】:2014-03-25 03:01:03
【问题描述】:

我只是想让一个程序将“测试”写入创建的文件。但是,当我运行下面的代码时,工作目录中没有文件。我在 Mac 上运行此代码并使用终端中的 gcc 进行编译。

    // writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example-1.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    if (myfile.fail())
       cout << "Fail" << endl;
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

【问题讨论】:

  • 有什么得到 cout 的吗?
  • 请显示您用于编译的确切命令,以及您用于执行的确切命令。
  • 位置是否可写?程序的输出是什么?你是如何编译和执行程序的。此外,您似乎正在使用 gcc,它是 GNU C 编译器来编译 c++ 程序。对于 c++ 程序,使用 g++ g++ -g -o
  • 您最好在打开文件后立即检查if (!myfile.good()) 然后cout &lt;&lt; "Unable to open file" &lt;&lt; endl; 在这种情况下您也没有打开文件,您正在检查它是否已打开,尝试@ 987654324@。另一件事是检查文件权限
  • 啊抱歉刚刚意识到你正在使用构造函数打开文件,也许在你的文件操作中添加一个 try catch 块。

标签: c++ loops ofstream


【解决方案1】:

我发布的所有代码均有效且有效。但是,我是在 Mac OSX 上使用 gcc 通过命令行进行编译的。该命令如下所示:

g++ -g nameofinputfile.cpp -o nameofoutput.out

这很好用,但是当您打开 .out 文件(编译文件)时,example-1.txt 文件会在存在 Documents、Desktop、Downloads 等的用户文件的根目录下创建。只需说明要创建它的位置。 Refer to this question 了解如何在代码中指定目录。

【讨论】:

    【解决方案2】:

    您必须使用fprintf() 在文本文件上写入文本。 例如:

    fp1=fopen("report.txt","a+");
    fprintf(fp1,"Port is open: %d\n\n",i);
    fclose(fp1);
    

    【讨论】:

    • 你可以在link看到更多细节
    猜你喜欢
    • 2012-01-22
    • 2010-12-27
    • 2011-08-06
    • 2011-12-12
    • 2017-07-08
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多