vc文件读写,用fstream和CStdioFile

vc文件读写,用fstream和CStdioFile。

第一种,用fstream:

#include <afx.h>
#include <iostream>
#include <fstream>

using namespace std;

// 如srcFile=D:\1.sql,则得到的destFile=D:\1_Result.sql
void GetResultFileName(char * destFile, char * srcFile)
{
	char *p;
	p = strrchr(srcFile, '\\');
	if(p)
	{
		memcpy(destFile, srcFile, p - srcFile + 1);
		srcFile = p + 1;
	}
	p = strrchr(srcFile, '.');
	if(p)
	{
		strncat(destFile, srcFile, p-srcFile);
		strcat(destFile, "_Result");
		strcat(destFile, p);
	}
	else
	{
		strcat(destFile, srcFile);
		strcat(destFile, "_Result");
	}
}

// 将srcString中的字符串替换后,写入outFile指向的文件中
void Replace(ofstream & outFile, char *srcString)
{
	char destString[1024] = {0};
	char *p, *pend, *q, *start;
	p = pend = q = start = NULL;
	int index = -1;
	while(srcString)
	{
		if(p = strstr(srcString, "to_date('"))
		{
			strncat(destString, srcString, p-srcString);		// 拷贝to_date前面的字符串
			p += 8;
			q = strstr(p, "'),");			// 搜索子字符串
			pend = strchr(p+1, '\'');		// 搜索特定字符
			strncat(destString, p, pend-p+2);
			srcString = q + 3;
		}
		else
		{
			strcat(destString, srcString);
			break;
		}
	}
	outFile<<destString<<endl;
}

void Transform(char *destFile, char * srcFile)
{
	ifstream inFile(srcFile);
	ofstream outFile(destFile);
	if(!inFile && !outFile)
	{
		cout<<"Open File["<<srcFile<<"] Failed."<<endl;
		return;
	}
	char line[1024];
	while(inFile.getline(line, 1024))
	{
//		cout<<"#"<<line<<"#"<<strlen(line)<<endl;
		Replace(outFile, line);
	}
	inFile.close();
	outFile.close();
}

void main()
{
	char srcFile[] = "D:\\11.sql";
	char destFile[100] = {0};
	GetResultFileName(destFile, srcFile);
	Transform(destFile, srcFile);
}

 

另一种,使用CStdioFile,主要代码如下(完整源码):

/*
	功能:将srcFile中所有的to_date('x', 'y')转换为'x', 并将时间改为格式:年-月-日 hh24:mi:ss
	@destFile:	输出文件全路径
	@srcFile:	输入文件全路径
*/
void CFileReplaceDlg::Transform(CString destFile, CString srcFile)
{
	CStdioFile inFile(srcFile, CStdioFile::modeRead);
	CStdioFile outFile(destFile, CStdioFile::modeCreate | CStdioFile::modeWrite);
	CString line;
	while(inFile.ReadString(line) != NULL)
	{
		Replace(outFile, line);
	}
	inFile.Close();
	outFile.Close();
}

界面如下:

vc文件读写,用fstream和CStdioFile_第1张图片

你可能感兴趣的:(Stream)