Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to write CStringArray to file, how can i do that ?

What I have tried:

CStringArray RegKeys;
for(int i = 0; i < RegKeys.GetCount(); i++)
	{

	CString str;
	
	str = RegKeys.GetAt(i);
	CFile file;
	if (!file.Open(_T("Test1.txt"),  CFile::modeWrite))
		return true;
	file.Write((LPCTSTR)str, str.GetLength() * sizeof(TCHAR));
	file.Close();

	}
Posted
Updated 28-Aug-17 3:45am

1 solution

Your code should actually write (and append) single strings from the array to the file.

But you should think about how the reader can distinguish the strings. This can be done by writing a new line sequence ("\r\n" Windows style or "\n" Unix style) creating a plain text file (which might be Unicode encoded) or by appending the trailing NULL bytes:
// New line separated
file.Write((LPCTSTR)str, str.GetLength() * sizeof(TCHAR));
file.Write(_T("\r\n"), 2 * sizeof(TCHAR));
// With null byte
file.Write(str.GetString(), (str.GetLength() + 1) * sizeof(TCHAR));

But the simplest method is using serialization which is supported by CStringArray:
CFile file(_T("Test1.txt"), CFile::modeCreate | CFile::modeWrite);
CArchive ar(&file, CArchive::store);
RegKeys.Serialize(ar);

Which method to use is up to you but you have to use a corresponding read method.

When not using serialization you should also move the file opening and closing out of the loop:
CFile file;
if (file.Open(_T("Test1.txt"),  CFile::modeWrite))
{
    // Loop to write strings goes here
    file.Close();
}
 
Share this answer
 
v2
Comments
srilekhamenon 29-Aug-17 1:02am    
Thanks

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