fstream未在C ++中创建文件

问题描述 投票:2回答:4

我已经检查了几个类似的问题,例如:Link 1Link 2

但是他们的答案都没有帮助我。在调试中花了很多小时之后,我无法检测到该错误。所以,我再次在这里问。

我程序的代码是:

#include<iostream>
#include<fstream>
#include<string.h>

using namespace std;

int main(){
    ofstream file;
    file.open("data.dat",fstream::out);
    file<<fflush;
    if(!file)
        cout<<"error"<<strerror(errorno);
    file.close();
    return 0;
}

这是程序处理文件的主要内容。该程序的其余部分处理一些数据并将其写入文件,我认为这既不相关也不影响文件处理。

有趣的是,程序没有闪烁任何错误。

c++ file-io fstream
4个回答
4
投票

您的代码通常可以进行少量更改,而只是在运行程序的当前工作目录中创建文件,而不是在可执行文件所在的目录中创建文件。但是,您可能还需要处理许多其他事项:

#include <iostream>
#include <fstream>
// if including things from the C standard library in a C++ program,
// use c[header] instead of [header].h; you don't need any here though.

using namespace std;

int main()
{
    // no need to call open(), the constructor is overloaded
    // to directly open a file so this does the same thing
    ofstream file("data.dat");

    if(!file)
    {
        cout << "Couldn't open file" << endl;
        return 1;
    }

    file.close();

    // return 0; is not needed, your program will automatically
    // do this when there is no return statement
}

有关为何无法打开文件的详细信息,请查看std::basic_ios::bad()std::basic_ios::bad()。使用C ++流进行文件处理时,您不需要执行std::basic_ios::fail()检查。


0
投票
std::basic_ios::fail()

0
投票

如果文件已打开,则可以在errnoint main(){ ofstream file; file.open("data.dat") // no need to call for ofstream ->fstream::out // file<<fflush; fflush won't work since there is nothing unwriten if(!file.is_open()) // use is_open(); cout<<"error"<<strerror(errorno); // write something to file file << " "; file.close(); return 0; } 的帮助下找到其位置。只需在文件打开且尚未关闭的地方放置一个断点即可。在调试器上运行程序,直到触发断点。然后使用以下命令:

GDB

其中procfs是程序的ls -l /proc/<pid>/fd 。文件的完整路径应在输出中的某个位置。


-1
投票
<pid>

主要区别:

  • 您没有PID
  • 您正在将“ errorno”传递给strerror(),而不是“ errno”,这是正确的数字。

这适用于Ubuntu 14.04(64位)。我使用无标志的g ++进行编译。

此外,我建议您不要使用using namespace std;一旦开始与其他库(例如Boost)集成(Boost的库可以与每个C ++标准库功能重叠),这将非常令人讨厌。

© www.soinside.com 2019 - 2024. All rights reserved.