views:

114

answers:

2

I wanna Write data into .txt file created by CFileDialog, in C++.

The problem I am facing is that below codes doesn't work, although there is no build error. The .txt file created by CFileDialog can not be found for some reason. What's wrong the code?

what's the efficient way to Write data into .txt file created by CFileDialog, in C++?

Thanks

CFileDialog dlg(FALSE, NULL, NULL, OFN_OVERWRITEPROMPT,
    _T("My Data File (*.txt)|*.txt||"));
if(dlg.DoModal() != IDOK)
     return;
CString filename = dlg.GetPathName();
ofstream outfile (filename);
int mydata = 10;
outfile << "my data:" << mydata << endl;
outfile.close();
+1  A: 

Why are you trying to use ofstream when you using MFC? You could use a CFile isn't it? Any specific reason why you are using ofstream?

Gangadhar
There's no rule saying you have to use MFC exclusively. Personally I like to use C++ standards where possible, and MFC specific stuff only where it makes more sense. For example I stopped using CArray years ago.
Mark Ransom
Yes, it looks really ugly to mix MFC with Ofstream. You are right, I can use CFile. The only reason I try Ofstream is it looks simple. Well, it is not a good idea.
Is there any equivalent part to CFileDialog in standard C++? Thanks
@younevertell, standard C++ doesn't include *any* GUI capabilites. So the answer is no.
Mark Ransom
Get it, thanks, Mark
Mark..there is a function called GetopenFileName which is a win32 function which almost equivalent to CFileDialog...is that right?
kiddo
+1  A: 

Without knowing about some settings I can only do a qualified guess.

E.g. depending on how you compile this, UNICODE or !UNICODE the CString behaves differently, i.e. maps to etiher CStringA or CStringW. The CString also behaves differently depending on the MFC version, in some cases there is a operator to implicit convert to a c string, in some not.

An ofstream normally expects a const char* as argument, so you may want to change it to

ofstream outfile(filename.GetBuffer(255)); 

in that case.

EDIT:

Did you check if you could open the file? from the above code it seems you assume success...

if ( outfile.is_open() )
...
Anders K.
CStringA will automatically convert to a const char* pointer, so there's no need to use GetBuffer. Microsoft's ofstream will take either a const char* or a const wchar_t* in the constructor, so either CString variant will work.
Mark Ransom
Yes as I said, it varies between the MFC versions in older version there was no automatic conversion so in order to be on the safe side(since I didn't know what version of MFC the OP was using) I gave the suggestion with GetBuffer
Anders K.