ofstream 不在 C++ 中创建文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12482725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:18:33  来源:igfitidea点击:

ofstream doesn't create file in C++

c++iostream

提问by BubbleTree

I'm trying to output every element of my array into a .txt file but for some reason it doesn't even create the file. I have both a cmd output and file output in my display method which is called from the main. The cmd output works perfectly but when i use ofstream to try and create a file and output the array's element to it, i don't see any text file created.

我试图将数组的每个元素输出到 .txt 文件中,但由于某种原因它甚至没有创建文件。我的显示方法中有一个 cmd 输出和文件输出,它是从 main 调用的。cmd 输出工作正常,但是当我使用 ofstream 尝试创建一个文件并将数组的元素输出到它时,我没有看到任何创建的文本文件。

ofstream ofs("TEST.txt");

if(!ofs)
    cout << "cannot use" << endl;
else
{
    for(int a=0; a < 12; a++)
    {
        for(int b=0; b < 12; b++)
        {

            cout << RandomArray[a][b] << "\t";
            ofs << RandomArray[a][b];
        }

        cout << "\n";
    }

}

ofs.close();

回答by mohaps

try this

尝试这个

#include <iostream>
#include <fstream>

#ifdef _WIN32
#include <windows.h>
#define SYSERROR()  GetLastError()
#else
#include <errno.h>
#define SYSERROR()  errno
#endif

int main(int argc, char** argv)
{
    std::ofstream of("TEXT.TXT");
    if(of.is_open())
    {
        of<<"Some text here"<<std::endl;
        of.flush();
        of.close();
        std::cout<<"wrote the file successfully!"<<std::endl;
    }
    else
    {
        std::cerr<<"Failed to open file : "<<SYSERROR()<<std::endl;
        return -1;
    }
    return 0;
}

The win32 GetLastError() #define isn't tested, as I don't have a windows box handy. The errno bit works. this will at least tell you what the error is if the file open fails

win32 GetLastError() #define 没有经过测试,因为我手边没有 Windows 框。errno 位有效。如果文件打开失败,这至少会告诉你错误是什么

回答by qdii

Your program is okay, it should work so long as ofstreamcan be created. I think that you are not looking in the right directory.

你的程序没问题,只要ofstream可以创建它就应该可以工作。我认为您没有在正确的目录中查找。