zoukankan      html  css  js  c++  java
  • c++文件指针Demo代码

    #include <iostream>
    #include <string>
    #include <vector>
    
    int main(){
        std::string infile = "./infile.txt";
        std::ifstream in(infile.c_str()); // 将string对象转为char*
        std::vector<long int> splitlist; // 存储分隔符位置
        splitchar = "
    "; // 将换行符作为分隔符
    
        if (! in.is_open()) {
            std::cerr << "Error: Invalid file " << infile << std::endl;
            return -1;
        }
    
        long int maxoffset = 0; // 如果文件没有以分隔符结尾则手动补一个文件结尾位置用
        while(in){
            maxoffset = in.tellg(); // tellg()报告当前指针位置
            if(splitchar == in.get()){
                splitlist.push_back(in.tellg()); // 保存文件中所有分隔符位置
            }
        }
        if (*(splitlist.end()-1) < maxoffset){
            splitlist.push_back(maxoffset+1);
        }
    
        in.close();
        in.open(infile.c_str(), std::ios::in); // 实测第一次全部文件读完需要重新打开文件。可能重置in的状态可以不用重新打开
    
        long int rowid = 10; // 以输出文件第十行为例
        std::vector<long int>::iterator iter = splitlist.begin()+(rowid-1); // 找到第十行起始的分隔符在文件中的位置
        in.seekg((*iter), std::ios::beg); // seekg()将文件指针跳转到指定位置
        for(int i=(*iter); i<(*iter)+((*(iter+1))-(*iter))-1; i++){
            // 从第十行起始的分隔符后开始,每次输出一个字符,直到输出完第十行的全部字符
            std::cout << (char)in.get() << std::flush;
        }
        std::cout << std::endl;
    
        return 0;
    }
    
  • 相关阅读:
    Aspose.Words三 创建表格
    Aspose.words一 DOM结构
    Aspose.words四 bookmark
    Aspose.Words五 MergeField
    为什么使用Reazor
    C#实现发送给QQ邮件
    T4模板之基础篇
    avalon子孙元素属性监听
    C#设置WebBrowser IE浏览器版本
    【GoLang】GoLang GOPATH 工程管理 最佳实践
  • 原文地址:https://www.cnblogs.com/esctrionsit/p/15176254.html
Copyright © 2011-2022 走看看