ofstream不会在C++中创建文件

Bub*_*ree 2 c++ iostream

我正在尝试将我的数组的每个元素输出到.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();
Run Code Online (Sandbox Code Playgroud)

moh*_*aps 5

试试这个

#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;
}
Run Code Online (Sandbox Code Playgroud)

win32 GetLastError()#define没有经过测试,因为我没有方便的窗口框.errno位工作正常.这至少会告诉你如果文件打开失败会出现什么错误