随笔 - 493  文章 - 0  评论 - 97  阅读 - 239万

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();
}

界面如下:

posted on   清清飞扬  阅读(2755)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
< 2010年12月 >
28 29 30 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示