如何编写cstringarray文件 [英] How to write a cstringarray to file

查看:66
本文介绍了如何编写cstringarray文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把CStringArray写入文件,我该怎么做?



我尝试过:



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();

	}

推荐答案

您的代码实际上应该将数组中的单个字符串写入(并追加)到文件中。



但你应该考虑读者如何区分字符串。这可以通过编写新的行序列(\\\\ nWindows样式或\ nUnix样式)来创建纯文本文件(可能是Unicode编码)或附加尾随的NULL字节来完成:

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));



但最简单的方法是使用序列化,这是支持 CStringArray


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();
}


这篇关于如何编写cstringarray文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆