Reputation: 606
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.
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();
Upvotes: 3
Views: 41634
Reputation: 1020
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
Upvotes: 7
Reputation: 12963
Your program is okay, it should work so long as ofstream
can be created. I think that you are not looking in the right directory.
Upvotes: 4