首页 > 编程语言 >C++实现文件内查找字符串

C++实现文件内查找字符串

时间:2024-01-13 21:59:13浏览次数:24  
标签:arrIndex auto C++ bufvolum 查找 file 字符串 include buf

实现概要:

  • 读取放入buf后 查找匹配的第一个字符 然后使用seek()移动文件指针,peek()查看 剩余的字符是否匹配
  • 如果剩余的字符匹配 把该字符串在文件中的位置 push 进一个vector<int>中 再继续查看剩余的文件内容
// str2.cpp -- capacity() and reserve()
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <malloc.h>
#include <windows.h>
#include <memory>
#include <iomanip>
//由于peek函数只能在当前文件指针下查看下一个字符, 应该自定义一个能移动到指定位置后查看下一个字符的peek.
#include <vector>
using namespace std;
int bufvolum = 512;
auto PeekInFile(ifstream& file, unsigned pos, unsigned peekNum)
{
    auto originPtr = file.tellg();
    string PeekedStr;
    PeekedStr.reserve(peekNum);
    if (!file.is_open())
    {
        return PeekedStr;
    }
    for (int i = 0; i < peekNum; ++i)
    {
        file.seekg(pos + i);
        if (file.fail())
        {
            cout << "seekg error!" << endl;
        }
        char ch = file.peek();
        PeekedStr.push_back(file.peek());

    }

    file.seekg(originPtr);
    return PeekedStr;
}

decltype(auto) FindInFile(ifstream& file, string substr, int pos = 0)
{
    vector<int> arrIndex;
    arrIndex.clear();
    if (!file.is_open())
    {
        return arrIndex;
    }
    file.seekg(pos);

    string buf;
    buf.reserve(bufvolum);
    buf.clear();

    auto j = substr.begin();
    auto getCount{0};
    ofstream  temp("temp.xml", ios_base::out);
    while (1)
    {
        file.read(buf.data(), bufvolum);
        buf.append(buf.data());
        auto i = buf.begin();
        auto backI = i;
        int realGet = file.gcount();
        getCount += realGet;

        for (; i < buf.end() ; ++i)
        {

            if (*i == *j)
            {
                buf.resize(bufvolum);
                int curIndex = getCount > bufvolum ? getCount - distance(i, buf.end()) : distance(buf.begin(), i) ;
                string PeekedStr(PeekInFile(file, curIndex, substr.size()));
                if (PeekedStr == substr)
                {
                    arrIndex.push_back(curIndex);
                }
            }
        }
        if (file.fail())
        {
            file.clear();
            break;
        }
        buf.clear();
    }
    return arrIndex;
}

int main()
{

    SetConsoleOutputCP(65001);
    ifstream fxml("C:\\Users\\34625\\Downloads\\cnblogs_blog_ComputerTech.20240111164025\\cnblogs.xml", ios_base::in); // create fis and associate with jamjar.txt
    if (!fxml.is_open())
    {
        cout << "\n open error!\n";
    }
    vector indexArr(move(FindInFile(fxml, "[TOC]"))) ;
    ofstream fwrite("xxxxx.xml");
    if (!fwrite.is_open())
    {
        fxml.close();
        return 0;
    }

    string buf;
    buf.reserve(bufvolum);
    for (auto i = indexArr.begin(); i < indexArr.end() ; ++i)
    {
        int need2write {0};
        if (i + 1 == indexArr.end())
        {
            auto originPos = fxml.tellg();
            fxml.seekg(0, ios_base::end);
            auto filesize = fxml.tellg();
            fxml.seekg(originPos);
            need2write = filesize - *i;
        }
        else
        {
            need2write = *(i + 1) - *i ;
        }

        int residual = need2write % bufvolum;
        unsigned time = need2write / bufvolum ;

        fxml.seekg(*i);
        if (!fxml.is_open() || fxml.fail() || fxml.bad())
        {
            cout << endl << "fxml error" << endl;
            system("pause");
        }

        while (time--)
        {
            if (fxml.fail() || fxml.bad())
            {
                cout << "failllllllllllllll" << endl;
                system("pause");
                break;
            }
            fxml.get(buf.data(), bufvolum + 1, EOF);
            int getNum = fxml.gcount();
            buf.append(buf.data());
            fwrite.write(buf.data(), fxml.gcount());//写入fwrite
            cout << buf.data();//
            buf.clear();
        }
        if (residual)
        {
            buf.clear();
            fxml.get(buf.data(), residual + 1, EOF );

            buf.append(buf.data());
            fwrite.write(buf.data(), residual);
            cout << buf.c_str();
        }
    }
    fwrite.close();
    fxml.close();
    system("pause");
    return 0;
}

标签:arrIndex,auto,C++,bufvolum,查找,file,字符串,include,buf
From: https://www.cnblogs.com/ComputerTech/p/17962969

相关文章

  • 【教3妹学编程-算法题】构造限制重复的字符串
    3妹:“太阳当空照,花儿对我笑,小鸟说早早早,你为什么背上炸药包”2哥:3妹,什么事呀这么开森。3妹:2哥你看今天的天气多好啊,最近一周都是大晴天,艳阳高照2哥:是啊,天气不冷不热的,很适合生活3妹:据说南方的小土豆都跑到北方滑雪了,哈哈哈哈2哥:泼水成冰好玩是好玩,但是一定要注意防寒哦,看新闻都有......
  • 从C向C++4——对象特性
    一.构造函数1.构造函数 在C++中,有一种特殊的成员函数,它的名字和类名相同,没有返回值,不需要用户显式调用(用户也不能调用),而是在创建对象时自动执行。这种特殊的成员函数就是构造函数(Constructor)。 我们通过成员函数setname()、setage()、setscore()分别为成员变量name、age、score......
  • C++ --- 智能指针
    一、智能指针存在的意义智能指针主要解决以下问题:(1)内存泄漏:内存手动释放,使用智能指针可以自动释放。(2)共享所有权指针的传播和释放,比如多线程使用同一个对象时析构问题。 智能指针的实现依赖于C++语言的RAII(资源获取即初始化)技术,即资源的获取和释放应该与对象的构造和析构分......
  • KY199 查找C
    C写个快排就行了。#include<stdio.h>#include<stdlib.h>#include<stdbool.h>intdivide(int*A,inthead,inttail){if(head==tail)returnhead;intx=A[head];while(head<tail){while(head<tail&&A[tail]&g......
  • SQL SERVER日期时间转字符串
    SQLSERVER日期时间转字符串一、sql server日期时间函数--当前系统日期、时间selectgetdate()--dateadd在向指定日期加上一段时间的基础上,返回新的datetime值--例如:向日期加上2天selectdateadd(day,2,'2004-10-15')--返回:2004-10-1700:00:00.000--datediff......
  • KY199 查找C++
      二分查找,没什么好说的。关键在于排成有序数组。然而C++调用sort就可以了。#include<iostream>#include<algorithm>#include<cstdlib>usingnamespacestd;booljudge(int*A,intn,intt){inthead=0;inttail=n-1;while(head<=tail){......
  • KY158 找xC++
    摆了几天,重新再来学习。‘把数据输入数组,然后遍历数组就行了,没什么难度。#include<iostream>#include<cstdlib>usingnamespacestd;intmain(){intn;while(cin>>n){int*A=(int*)malloc(sizeof(int)*n);for(inti=0;i<n;i++){......
  • Qt/C++编写视频监控系统83-自定义悬浮条信息
    一、前言一般视频控件上会给出个悬浮条,这个悬浮条用于显示分辨率或者一些用户期望看到的信息,一般常用的信息除了分辨率以外,还有帧率、封装格式、视频解码器名称、音频解码器名称、实时码率等,由于实际的场景不一样,用户希望能过自定义勾选开启哪些信息,开启的就显示,不开启的则可以不......
  • C++ 单例模式以及内存管理
    引用:https://zhuanlan.zhihu.com/p/37469260https://www.cnblogs.com/xiaolincoding/p/11437231.htmlhttps://blog.csdn.net/unonoi/article/details/121138176单例模式:一个类在全局范围内只有一个实例化的对象核心:构造函数是私有的,防止外界创建单例类的对象。使用类内的......
  • c++ opencv直线检测
     #include<opencv2/opencv.hpp>#include<opencv2/highgui/highgui.hpp>#include<opencv2/imgproc/imgproc.hpp>usingnamespacecv;intmain(intargc,char**argv){//读取图像Matsrc=imread(argv[1],CV_LOAD_IMAGE_COLOR);if......