-
#include <cstdio>
-
#include <iostream>
-
#include <cstring>
-
#include <cstdlib>
-
-
using namespace std;
-
-
class CFileUnit
-
{
-
public:
-
CFileUnit();
-
~CFileUnit();
-
void GetFilePath(const char* psrFilePath);
-
void OpenFile();
-
bool isOpen();
-
void GetSQLStatement(char* psrStmt);
-
static void Erase(char* psrStmt);
-
bool isEndFile();
-
private:
-
int m_iPos;
-
FILE* m_pfFile;
-
char m_srFilePath[128];
-
bool m_bEndFile;
-
};
-
-
CFileUnit::CFileUnit()
-
{
-
m_iPos = 0;
-
m_pfFile = NULL;
-
m_bEndFile = false;
-
memset(m_srFilePath, 0, sizeof(m_srFilePath));
-
}
-
-
CFileUnit::~CFileUnit()
-
{
-
if (!isOpen())
-
{
-
fclose(m_pfFile);
-
}
-
}
-
-
bool CFileUnit::isEndFile()
-
{
-
if (m_bEndFile)
-
{
-
return true;
-
}
-
return false;
-
}
-
-
bool CFileUnit::isOpen()
-
{
-
if (m_pfFile != NULL)
-
{
-
return false;
-
}
-
else
-
{
-
return true;
-
}
-
}
-
-
void CFileUnit::GetFilePath(const char* psrFilePath)
-
{
-
if (NULL == psrFilePath)
-
{
-
return;
-
}
-
memset(m_srFilePath, 0, sizeof(m_srFilePath));
-
strncpy(m_srFilePath, psrFilePath, sizeof(m_srFilePath));
-
}
-
-
void CFileUnit::OpenFile()
-
{
-
m_pfFile = fopen(m_srFilePath, "r");
-
if (NULL == m_pfFile)
-
{
-
}
-
}
-
-
void CFileUnit::GetSQLStatement(char* psrStmt)
-
{
-
if (NULL == psrStmt)
-
{
-
}
-
-
char chTmp = 0;
-
char chPrev = 0;
-
int iLen = 0;
-
bool bInString = false;
-
char srTmp[128] = {'\0'};
-
-
while ((chTmp = fgetc(m_pfFile)) != EOF)
-
{
-
if ('\'' == chTmp)
-
{
-
if (chPrev != '\\')
-
{
-
if (!bInString)
-
{
-
bInString = true;
-
}
-
else
-
{
-
bInString = false;
-
}
-
}
-
}
-
else if (';' == chTmp && !bInString)
-
{
-
fseek(m_pfFile, m_iPos - iLen, SEEK_SET);
-
memset(srTmp, 0, sizeof(srTmp));
-
fread(srTmp, 1, iLen + 1, m_pfFile);
-
strncpy(psrStmt, srTmp, sizeof(srTmp));
-
CFileUnit::Erase(psrStmt);
-
m_iPos++;
-
return;
-
}
-
chPrev = chTmp;
-
iLen++;
-
m_iPos++;
-
}
-
m_bEndFile = true;
-
}
-
-
void CFileUnit::Erase(char* psrStmt)
-
{
-
char* psrTra = psrStmt;
-
char* psrSt = psrStmt;
-
-
while (*psrTra != '\0')
-
{
-
if ('\n' == *psrTra || '\r' == *psrTra || ' ' == *psrTra)
-
{
-
psrTra++;
-
}
-
else
-
{
-
*psrSt++ = *psrTra++;
-
}
-
}
-
*psrSt = '\0';
-
}
-
-
int main()
-
{
-
char str[128] = {'\0'};
-
CFileUnit fileUnit;
-
-
fileUnit.GetFilePath("tempfile");
-
fileUnit.OpenFile();
-
-
while (1)
-
{
-
fileUnit.GetSQLStatement(str);
-
if (fileUnit.isEndFile())
-
{
-
break;
-
}
-
cout << str << endl;
-
}
-
-
return 0;
-
}
tempfile文件内容:'\'name\''; ';\';;;'; update('\'\'');
缺陷:
遇到的问题:第90行和对应的113行。设置srTmp大小为1024字节,这样113执行时,覆盖了对象中其他属性的值,被改为0了,导致之后的函数调用出现“Segment error”。strncpy
(psrStmt
, srTmp
, sizeof
(srTmp
));也应该改为strncpy
(psrStmt
, srTmp
, sizeof(
psrStmt)
);
阅读(870) | 评论(0) | 转发(0) |