Rami Far
Rami Far

Reputation: 404

How to start reading file from a particular position c++

I am reading a file using fstream and getline functions. I want to give a starting position e.g. my file has 13 lines I want to start reading it from 7th line for example. Here is my code:

#include<iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include<iterator> // for iterators
#include<map>
using namespace std;

int main() 
{
    string line;
    int start= 7;
    unsigned long int index;
    For( int z=1; z<=13; z++){
    if (f_node.is_open())
    {
        getline(f_node, line);
        if ((line.find("$EndNodes") != string::npos))
        {
            cout << "$EndNodes found file closed .... " << endl;
            f_node.close();
            return false;
        }

        // Point index.

        int i = 0;
        int j = line.find_first_of(" ", i);
        index = strtoul((line.substr(i, j)).c_str(), NULL, 0);//
}

} This is my file I am reading only indexes and I want to start it from 7th index How to do it?

Upvotes: 0

Views: 5985

Answers (2)

zdf
zdf

Reputation: 4808

"there is no way to tell code the starting position like seekg and tellg?" No. NL is just like any other character, it does not receive any special treatment.

You simply must scan the stream, counting the new-line character:

std::istream& seek_line(std::istream& is, const int n, std::ios_base::seekdir way = std::ios_base::beg)
{
  is.seekg(0, way);
  int i = 0;
  char c;
  while (is.get(c) && i < n)
    if (c == '\n')
      ++i;
  is.putback(c);
  return is;
}

And this is how you use the above function:

int main()
{
  using namespace std;

  ifstream is{ "c:\\temp\\test.txt" };
  if (!is)
    return -1;

  if (!seek_line(is, 3))
    return -2;

  string s;
  getline(is, s);
  cout << s << endl;

  return 0;
}

Upvotes: 0

Shawn
Shawn

Reputation: 52449

To discard some number of lines, something like:

#include <fstream>
#include <string>

int main() {
  std::ifstream infile{"myfile.txt"};
  std::string line;
  int starting_line = 7;

  // Read and discard beginning lines
  for (int n = 1; n < starting_line; n += 1) {
    if (!std::getline(infile, line)) {
      // Error or premature end of file! Handle appropriately.
    }
  }

  while (std::getline(infile, line)) {
    // Do something with the lines you care about.
  }

  return 0;
}

Except with actual error checking and handling and such.

Upvotes: 2

Related Questions