【问题标题】:How do I get my c++ program to create a new file?如何让我的 c++ 程序创建一个新文件?
【发布时间】:2013-12-16 19:33:32
【问题描述】:

我试过四处打听并在谷歌上搜索答案。它不会在我的文档文件夹中创建 .txt 文件。无论我尝试什么,我都没有收到任何错误,并且代码一直运行到 main 结束。 1. 我的输入是正确的。我检查了cout。 2. 我把 C:\users\Bryan\Documents\Points.txt 作为我的目录

int main()
{
//...
std::string filename;
cout << "Enter output filename: ";
std::getline(cin, filename);

ofstream ost(filename.c_str());
if (!ost) cerr << "can't open output file: " << filename << endl;

    for(int i=0; i<points.size(); ++i)
        ost<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;
        cout <<"got here 6"<<endl;
//...
}

我添加了 close(),但忘记了返回 0,并且它工作了一次。 然后我添加了return 0,无论我尝试多少次,它都不会创建新文件,但不会抛出错误。 我看不出我做错了什么。有人吗?

int main()
{
    cout <<"got here 1"<<endl;

    cout << "Please enter the file name: ";
    char name[90];
    cin.getline(name, 90);

    cout <<"got here 2"<<endl;
    ifstream ifs(name);
    if(!ifs) error("can't open input file ",name);

    vector<Point> points;
    Point p;
    while(ifs>>p)points.push_back(p);
    cout <<"got here 3"<<endl;

    for(int i=0; i<points.size(); ++i)
        cout<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;

std::string filename;
cout << "Enter output filename: ";
std::getline(cin, filename);

ofstream ost(filename.c_str());
if (!ost) cerr << "can't open output file: " << filename << endl;

    for(int i=0; i<points.size(); ++i)
        ost<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;
        cout <<"got here 6"<<endl;

    ost.close();

    keep_window_open();

      return 0;

   }

【问题讨论】:

  • 可能是文件出了问题(损坏或类似情况)。您是否尝试重新启动计算机?
  • 我很确定这是愚蠢的 Avast 防病毒软件。它总是要求我批准运行应用程序,并阻止许多程序,例如,当我连接智能手机时,防火墙会阻止我的互联网连接。
  • 仅供参考:我又试了一次。 Avast 中断 MS c++ 编译器让我可以选择在沙盒中运行,或者正常运行。一开始我选择了沙盒,因为它只是少了一次鼠标点击。我没有理由不这样做,因为我一直在关注 Stroustrup 的教科书,而且本书第一部分的简单程序不受沙盒的影响。我猜 Avast 的沙盒会阻止创建任何新文件。

标签: c++ file-io iostream


【解决方案1】:

看来,您最后忘记关闭文件了。尝试添加 ost.close() 以指示您的流刷新到文件。

【讨论】:

  • 终于做到了!但是 Stroustrup 说您不需要 close(),而且当代码超出范围时让文件夹自行关闭实际上是更好的代码。这里发生了什么?也许问题是我把代码放在 main() 中?
  • @user2904033 这种行为差异令人惊讶。析构函数应该隐式关闭文件。在我的带有 gcc 4.6(和相应的 glibc)的 Ubuntu 上,无论是否明确调用 close(),都会创建该文件,即使我没有向其写入任何内容。也许您的 C++ 实现(库)中存在错误。
  • 我正在使用 stroustrup 从他的网站提供的 std_lib_facilities.h,以及 main() 末尾的 keep_window_open() 函数。看来我也忘了返回 0;从主要。这些是否可能是罪魁祸首?
【解决方案2】:

尝试将 std::ofstream::out 添加到 ofstream 构造函数中,并使用 isOpen 检查文件是否实际打开。

int main()
{
//...
std::string filename;
cout << "Enter output filename: ";
std::getline(cin, filename);

ofstream ost(filename.c_str(), std::ofstream::out);
if (!ost.isOpen()) cerr << "can't open output file: " << filename << endl;

    for(int i=0; i<points.size(); ++i)
        ost<<'('<<points[i].x<<','<<points[i].y<<')'<<endl;
        cout <<"got here 6"<<endl;
//...
}

【讨论】:

  • 大错特错。带路径的构造函数自动打开文件,析构函数自动关闭文件。
  • 编辑后,我的第一条评论不再相关。但是现在:out 已经是ofstream 的默认模式:link。另外,我猜你所说的“isOpen”是指is_open
猜你喜欢
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2012-12-09
相关资源
最近更新 更多