如何将cstring保存到文件中 [英] How ro save the cstring into the file

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

问题描述

我想将cstring写入文件,但是我无法将所有数据写入文件





我尝试过:



CString data =[ERROR]:2018-03-21 06:51:02 GMT

 fwrite(data,sizeof(data),1,stream); 

fprintf(stream,\ n);
fflush(stream);
fclose(stream);



我在文件中获取o / p为[ERR

如果你能纠正我我在这里做错了什么

解决方案

除了使用正确的长度,写入文件的内容还取决于你的项目是否是Unicode。



编写 CString 内容正确的正确解决方案是:

 fwrite(data.GetString(),sizeof(TCHAR),data.GetLength(),stream); 



使用Unicode构建时, CString 内容存储在内部为 wchar_t ,其大小为两个字节。对于非Unicode构建,它存储为 char TCHAR 类型是根据Unicode设置的相应字符类型。因为 CString :: GetLength()返回字符数,所以大小必须乘以字符大小。



如果您有Unicode构建但想要写入ANSI文件,则必须首先将字符串转换为ANSI或使用ANSI字符串:

 / /使用ANSI字符串
CStringA dataA =[ERROR]:2018-03-21 06:51:02 GMT;
fwrite(dataA.GetString(),1,dataA.GetLength(),stream);

//用任何构建选项编写ANSI
CString dataAny = _T([ERROR]:2018-03-21 06:51:02 GMT);
//这将使用Unicode构建转换为ANSI,否则为
CStringA dataA(dataAny);
fwrite(dataA.GetString(),1,dataA.GetLength(),stream);

注意使用 CStringA 这是 char 版本。


sizeof 返回对象的大小,而不是这是内容!

你需要的是 CString: :GetLength [ ^ ]

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

解决方案

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.


sizeof returns the size of the object, not it's content!
What you need is CString::GetLength[^]


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

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