Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file content from specific position to another specific position

Tags:

c++

file

I want a part of file content by specifying the beginning of position and specifying the end of position.

I'm using seekg function to do that, but the function only determine the beginning position, but how determine the end position.

I'm did code to get the content of file from specific position to end of file, and save each line in item of array.

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

For example
The following is the file content:

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

I want to get only the following part:

39.
beside Marten st.
2/8/2013.
like image 318
Lion King Avatar asked Jan 12 '23 18:01

Lion King


2 Answers

Since you know the start and end of the block you want to read from the file you can use 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);
}

Or if you insist on using naked pointers and managing the memory yourself...

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
}
like image 93
Captain Obvlious Avatar answered Jan 26 '23 22:01

Captain Obvlious


Read the reference for fstream. In the seekg function, they define some ios_base stuff you want. I think you're looking for:

file.seekg(0,ios_base::end)

Edit: Or perhaps you want this? (Taken straight from the tellg reference, modified a bit to read a random block that I pulled out of thin air).

// 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;
}
like image 24
Suedocode Avatar answered Jan 26 '23 22:01

Suedocode