加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 从特定位置获取文件内容到另一个特定位置

发布时间:2020-12-16 09:46:43 所属栏目:百科 来源:网络整理
导读:我想通过指定位置的开头和指定位置的结尾来获取文件内容的一部分. 我正在使用seekg函数来执行此操作,但该函数仅确定开始位置,但如何确定结束位置. 我做了代码,将文件内容从特定位置获取到文件末尾,并将每行保存在数组项中. ifstream file("accounts/11619.tx
我想通过指定位置的开头和指定位置的结尾来获取文件内容的一部分.

我正在使用seekg函数来执行此操作,但该函数仅确定开始位置,但如何确定结束位置.

我做了代码,将文件内容从特定位置获取到文件末尾,并将每行保存在数组项中.

ifstream file("accounts/11619.txt");
if(file != NULL){
   char *strChar[7];
   int count=0;
   file.seekg(22); // Here I have been determine the beginning position
   strChar[0] = new char[20];
   while(file.getline(strChar[count],20)){
      count++;
      strChar[count] = new char[20];
}

例如
以下是文件内容:

11619.
Mark Zeek.
39.
beside Marten st.
2/8/2013.
0

我想只得到以下部分:

39.
beside Marten st.
2/8/2013.

解决方法

由于您知道要从文件中读取的块的开头和结尾,因此可以使用ifstream :: read().

std::ifstream file("accounts/11619.txt");
if(file.is_open())
{
    file.seekg(start);
    std::string s;
    s.resize(end - start);
    file.read(&s[0],end - start);
}

或者如果你坚持使用裸指针并自己管理内存……

std::ifstream file("accounts/11619.txt");
if(file.is_open())
{
    file.seekg(start);
    char *s = new char[end - start + 1];
    file.read(s,end - start);
    s[end - start] = 0;

    // delete s somewhere
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读