在文本文件C ++上编写

时间:2014-03-25 03:01:03

标签: c++ loops ofstream

我只是想让一个程序写下来"测试"到创建的文件。但是,当我运行下面的代码时,工作目录中没有文件。我在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;
}

2 个答案:

答案 0 :(得分:0)

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

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

这样可以正常工作,但是当您打开.out文件(编译文件)时,将在Users文件的根目录中创建example-1.txt文件,其中存在Documents,Desktop,Downloads等。只需要说明它的创建位置。 Refer to this question了解如何在代码中指定目录。

答案 1 :(得分:0)

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

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