1.代码(源码)
#pragma once
class Log
{
public:
int m_WirteOneCount;
FILE* OpenTxt(CString& strTxtName,char* strOpenStyle);
int CloseTxt(FILE*& pFile);
void WirteDataTxt(int comno, CString ncha);
int WriteTxt(FILE* pFile, CString strTxt);
};
#include "pch.h"
#include "Log.h"
void Log::WirteDataTxt(int comno, CString ncha)
{
CString str = _T("");
str.Format(_T("device%d.txt"), comno);
m_WirteOneCount++;
if (m_WirteOneCount >= 1000)
{
m_WirteOneCount = 0;
FILE* pFile = OpenTxt(str, "w");
WriteTxt(pFile, ncha);
CloseTxt(pFile);
}
else
{
FILE* pFile = OpenTxt(str, "a");
WriteTxt(pFile, ncha);
CloseTxt(pFile);
}
}
FILE* Log::OpenTxt(CString& strTxtName, char* strOpenStyle)
{
//打开文件
FILE* pFile = NULL;
pFile = fopen((LPCTSTR)strTxtName, strOpenStyle);
if (NULL != pFile)
{
return pFile;
}
else
return NULL;
}
int Log::WriteTxt(FILE* pFile, CString strTxt)
{
//判断文件是否打开
if (NULL != pFile)
{
COleDateTime oleDT = COleDateTime::GetCurrentTime();
CString strDT = oleDT.Format();
CString strTxt1 = _T("");
//写字符串
int iWritten = -1;
if (("\r\n" == strTxt) || ("\r\n\r\n" == strTxt))
{
strTxt1 = strTxt;
}
else
{
strDT += " ";
strDT += strTxt;
strTxt1 = strDT;
}
iWritten = fprintf(pFile, "%s\r\n", (LPCTSTR)strTxt1);
if (iWritten > 0)
{
return 0;
}
else
return 1;
}
else
return 2;
}
int Log::CloseTxt(FILE*& pFile)
{
//判断文件是否打开
if (NULL != pFile)
{
int iRet = fclose(pFile);
if (0 == iRet)
{
pFile = NULL;
return 0;
}
else
return 1;
}
else
return 0;
}
void CfilefprintfDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CString str = _T("读取成功");
Log log;
log.WirteDataTxt(2, str);
}
2.运行
3.问题处理
3.1 问题1
3.2 问题2
3.3 关于字符问题的补充说明
LPCTSTR是一个windows API数据类型。与其相关还有两个类型:LPCSTR和LPCWSTR
LPCSTR:根据windows API数据类型的命名规律,LP表示该变量是一个指针,C表示是常量(const),STR表示的是字符串。因此LPCSTR是一个const char*类型。这是一个windows(ANSI)字符串常量,注意是多字节编码的。
LPCWSTR:而W表示的是宽字符,因此LPCWSTR表示的也是字符串常量,不过是Unicode编码的。
在WinNT.h中的定义:
typedef const char* LPCSTR;
typedef const wchar* LPCWSTR;
最后再看LPCTSTR:根据环境配置,如果定义了UNICODE宏,则是LPCWSTR类型,否则是LPCSTR类型。
"_T"宏:当工程是Unicode编码时,_T将括号内的字符串以Unicode方式保存;当工程是多字节编码时,_T将括号内的字符串以ANSI方式保存,这种情况相当于不起作用。
"L"宏:不管编码环境是什么,都是将其后面的字符串以Unicode方式保存。