【发布时间】: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 << "Unable to open file" << endl;在这种情况下您也没有打开文件,您正在检查它是否已打开,尝试@ 987654324@。另一件事是检查文件权限 -
啊抱歉刚刚意识到你正在使用构造函数打开文件,也许在你的文件操作中添加一个 try catch 块。