积极答复者
文件写操作的几个问题【急】

问题
-
我在写文件时候遇到了问题,请教大家:
我的目的是要在test.txt文本中得到如下格式数据:
1111,2222
3333,4444
可是结果为
1 1 ,2 2 3 3 ,4 4
-------------------------------代码如下----------------------------------------------------------
CFile cf(L"test. txt", CFile::modeCreate|CFile::modeWrite|CFile::modeRead;
cf.Write(L"1111",4);
cf.Write(L",",1);
cf.Write(L"2222",4);
cf.Write(L"\r\n",2);
cf.Write(L"1111",4);
cf.Write(L",",1);
cf.Write(L"2222",4);
cf.Write(L"\r\n",2);
-----------------------------代码结束---------------------------------------------------------
出现的问题怎么解决??
(1) 少写字符,有些变成了空格。
(2)写回车换行不成功。
谢谢大家
另外还有一个问题,
大家一般写入文件用什么操作,MFC的CFile操作,还是API的CreateFile。
有啥区别?
答案
-
CFile cf(L"C:\\test.txt", CFile::modeCreate|CFile::modeWrite|CFile::modeRead); cf.Write(L"1111",8); cf.Write(L",",2); cf.Write(L"2222",8); cf.Write(L"\r\n",4); cf.Write(L"1111",8); cf.Write(L",",2); cf.Write(L"2222",8); cf.Write(L"\r\n",4); cf.Close(); CFile::Write
virtual void Write( const void* lpBuf, UINT nCount );
throw( CFileException );Parameters
lpBuf
A pointer to the user-supplied buffer that contains the data to be written to the file.
nCount
The number of bytes to be transferred from the buffer. For text-mode files, carriage return–linefeed pairs are counted as single characters.
nCount 是要从buffer中写入的字节数。楼主使用的是UNICODE类型,长字符表示每个字符占两个字节,所以nCount要加倍。
对于MFC的CFile操作,还是API的CreateFile。建议如果可以用MFC尽量不要直接使用WindowsAPI。因为你的整体框架和大部分的调用都在使用MFC,调用API会导致一些错误。CreateThread和afxBeginThread就是一个例子。afxBeginThread帮你做了一些事情。保存线程上下文的结构都是不一样的。
另外对于只进行写操作的时候,不要使用CFile::modeRead这会使性能下降- 已标记为答案 beyard 2009年2月21日 16:38
全部回复
-
CFile cf(L"C:\\test.txt", CFile::modeCreate|CFile::modeWrite|CFile::modeRead); cf.Write(L"1111",8); cf.Write(L",",2); cf.Write(L"2222",8); cf.Write(L"\r\n",4); cf.Write(L"1111",8); cf.Write(L",",2); cf.Write(L"2222",8); cf.Write(L"\r\n",4); cf.Close(); CFile::Write
virtual void Write( const void* lpBuf, UINT nCount );
throw( CFileException );Parameters
lpBuf
A pointer to the user-supplied buffer that contains the data to be written to the file.
nCount
The number of bytes to be transferred from the buffer. For text-mode files, carriage return–linefeed pairs are counted as single characters.
nCount 是要从buffer中写入的字节数。楼主使用的是UNICODE类型,长字符表示每个字符占两个字节,所以nCount要加倍。
对于MFC的CFile操作,还是API的CreateFile。建议如果可以用MFC尽量不要直接使用WindowsAPI。因为你的整体框架和大部分的调用都在使用MFC,调用API会导致一些错误。CreateThread和afxBeginThread就是一个例子。afxBeginThread帮你做了一些事情。保存线程上下文的结构都是不一样的。
另外对于只进行写操作的时候,不要使用CFile::modeRead这会使性能下降- 已标记为答案 beyard 2009年2月21日 16:38