Click here to Skip to main content
15,894,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i want to write the cstring into the file but iam not able to write the all datat into the file 


What I have tried:

CString data = "[ERROR]: 2018-03-21 06:51:02 GMT"
fwrite(data, sizeof(data), 1, stream);
    
        fprintf(stream, "\n");
        fflush(stream);
        fclose(stream);

im getting o/p in file as "[ E R R"
could you please correct me if i am doing anything wrong here
Posted
Updated 20-Mar-18 21:59pm
Comments
Richard MacCutchan 21-Mar-18 5:07am    
The simple answer is not to use fwrite, as that is basic C runtime. Use proper MFC classes for everything.

Besides using the correct length what is written to file depends also if your project is Unicode or not.

The correct solution to write the CString content "as it is" is:
fwrite(data.GetString(), sizeof(TCHAR), data.GetLength(), stream);

With Unicode builds, the CString content is stored internally as wchar_t which has a size of two bytes. With non-Unicode builds, it is stored as char. The TCHAR type is the corresponding character type according to the Unicode setting. Because CString::GetLength() returns the number of characters, the size has to be multiplied with the size of a character.

If you have a Unicode build but want to write to an ANSI file, you have to convert the string first to ANSI or use an ANSI string:
// Using ANSI string
CStringA dataA = "[ERROR]: 2018-03-21 06:51:02 GMT";
fwrite(dataA.GetString(), 1, dataA.GetLength(), stream);

// Writing ANSI with any build option
CString dataAny = _T("[ERROR]: 2018-03-21 06:51:02 GMT");
// This converts to ANSI with Unicode builds and copies otherwise
CStringA dataA(dataAny);
fwrite(dataA.GetString(), 1, dataA.GetLength(), stream);
Note the usage of CStringA which is the char version.
 
Share this answer
 
sizeof returns the size of the object, not it's content!
What you need is CString::GetLength[^]
 
Share this answer
 
Comments
Member 13089825 21-Mar-18 3:19am    
i have used like below but still i am not able write all the string into the file
fwrite(data, data.GetLength(), 1, stream);
could you please correct me
OriginalGriff 21-Mar-18 4:07am    
See Jochen's complete solution 2!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900