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

Get file content from specific position to another specific position

本文关键字:位置 定位 获取 另一个 文件      更新时间:2023-10-16

我想要通过指定位置的开始和位置的结束来获得文件内容的一部分。

我用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
}

读取fstream的引用。在seekg函数中,它们定义了一些您想要的ios_base内容。我想你在找:

file.seekg(0,ios_base::end)

编辑:或者你想要这个?(直接取自电视参考,修改了一点,读取了我凭空提取的随机块)。

// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream
int main () {
  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    is.seekg(-5,ios_base::end); //go to 5 before the end
    int end = is.tellg(); //grab that index
    is.seekg(22); //go to 22nd position
    int begin = is.tellg(); //grab that index
    // allocate memory:
    char * buffer = new char [end-begin];
    // read data as a block:
    is.read (buffer,end-begin); //read everything from the 22nd position to 5 before the end
    is.close();
    // print content:
    std::cout.write (buffer,length);
    delete[] buffer;
  }
  return 0;
}

首先可以使用

seekg()

要设置读取位置,则可以使用

read(buffer,length)

阅读意向。

例如,您想要读取一个名为test.txt的文本文件中从第6个字符开始的10个字符。

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
std::ifstream is ("test.txt", std::ifstream::binary);
if(is)
{
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(5, is.beg);
char * buffer = new char [length];
is.read(buffer, 10);
is.close();
cout << buffer << endl;
delete [] buffer;
}
return 0;
}

但在您的情况下,为什么不使用getline()呢?