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

4

我希望能够通过指定起始位置和结束位置来获取文件内容的一部分。

我使用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.

1
哦,请使用 std::stringstd::getline - Nawaz
@Nawaz:但我想使用C风格的字符串。 - Lion King
如果您知道起始位置结束位置,难道不可以计算要读取的字符数,并将其作为getline()的第二个参数传递吗? - Tariq M Nasim
3个回答

6

既然你知道要从文件中读取的块的起始点和终止点,你可以使用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
}

谢谢,但我想使用C风格的字符串。 - Lion King
@LionKing,你能不能不要使用s.c_str(),或者使用char *代替string; - Pranit Kothari
@LionKing 不确定为什么你坚持使用裸指针,但我已经更新了我的示例。 - Captain Obvlious
@Captain Obvlious:请问您能告诉我s[end - start] = 0;的好处是什么吗? - Lion King
@LionKing 它会在字符串的末尾添加一个空终止符。 - Captain Obvlious

2

请阅读fstream的参考文献。在seekg函数中,他们定义了一些你需要的ios_base内容。我认为你正在寻找:

file.seekg(0,ios_base::end)

编辑:或者你想要这个?(直接从tellg参考中获取,稍作修改以读取我从空气中提取出来的随机块)。

// 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;
}

谢谢,但我知道ios_base :: end,我不想读取文件的结尾。我想要从特定文件偏移量到特定文件偏移量的文件内容的一部分。 - Lion King
你是指tellg吗?我相信该参考文献会告诉你想知道的内容... - Suedocode

1
首先,你可以使用


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()?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接