|
1、创建文件
- int _tmain(int argc,TCHAR* argv)
- {
- //创建文件对象
- CFile file;
- //创建1.txt文件。如果存在就用存在的,没有就新建
- CFileException ex;
- file.Open(_TEXT("D:\\temp\\a\\aa\\1.txt"),
- CFile::modeCreate|
- CFile::modeNoTruncate,
- &ex);
-
- //关闭文件
- file.Close();
-
-
- return 0;
- }
复制代码
2、读文件内容
- int _tmain(int argc,TCHAR* argv)
- {
- //创建文件
- CFile file;
-
- //打开文件,并请求写入访问权限
- CFileException ex;
- file.Open(_T("D:\\temp\\a\\aa\\1.txt"), CFile::modeRead, &ex);
- int nfileChar = file.GetLength(); //坑点,不能用THAR* 只能用char*
- char* lpBuf = new char[nfileChar];
- memset(lpBuf, '\0', nfileChar); //根据内容长度,动态分配缓存
- file.Read(lpBuf,nfileChar); //读取文件内容到 缓存
- CString msg = CA2W(lpBuf,CP_UTF8); //将窄字节转为宽字节 转的时候,用CA2W直接用指针接受也会用问题,必须要用CString来过渡下,要不就的用MutilByWchar..Win32API
- //输出结果
- std::wcout.imbue(std::locale("chs"));//处理w_cout 不显示中文的情况
- wcout << (const wchar_t*)msg;
- delete[] lpBuf;
- file.Close();
-
- return 0;
- }
复制代码
3、写文件内容
- int _tmain(int argc,TCHAR* argv)
- {
- CFile cfile; //创建文件
- //打开文件
- CFileException ex;
- cfile.Open(_T("D:\\temp\\a\\aa\\1.txt"),
- CFile::modeNoTruncate|CFile::modeWrite,
- &ex);
- char msg[256] = {0};
- sprintf_s(msg, "哈哈哈%d", 123); //文件类CFile 最好用char* 窄字节 写入和读取
-
- cfile.SeekToEnd(); //移动光标在文本的最后一行实现追加,默认光标在第一个字节处,每次写都会覆盖原有文件的内容。
- cfile.Write(msg,(strlen(msg)) * sizeof (char)); //将内容写入文件缓冲区 //不要空格,如果直接传256,后面的很多个0都会也追加到文件中
- cfile.Flush(); //刷新缓存区,将内容写入到文件中
- cfile.Close();
-
- return 0;
- }
复制代码
|
上一篇: 复杂的宽窄字节数据类型
|