R
R
Roman Gamretsky2014-10-25 18:55:40
C++ / C#
Roman Gamretsky, 2014-10-25 18:55:40

How to read a section of a line (text file) in C++?

The task is this. There is a file from which it is necessary to read the words at the given positions [10;20], [23;40] (for example). Is it possible to somehow read them at specified intervals directly from the file using fstream, or with a string variable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ruchkin, 2014-10-25
@VoidEx

Use seekg and read

I
Ivan Ershov, 2014-10-25
@iwanerhov

So ! You need to know the file size! (for 1 byte encoding)

int GetSizeFile(const char * filename)
{
  std::ifstream file(filename, std::ios_base::binary);
  int size = 0;
  
  file.seekg(0, std::ios_base::end);
  size = (int)file.tellg();
  
  return size;
}

Now you know the file size! And you can still write your own function or method where you will use the seekg method to jump over the file
. But the method for copying! By the way, the method is canonical!
bool CopyFiles(const char * pathWithName, const char * outputPathAndName)
{
  std::ifstream in(pathWithName, std::ios::in | std::ifstream::binary);
  std::ofstream out(outputPathAndName, std::ios::out| std::ofstream::binary);
  
  if (!in)
    return false;
  if (!out)
    return false;

  const int bufSize = 4096;
  char * buffer = new char[bufSize];
  
  while (!in.eof())
  {
      in.read(buffer, bufSize);
      if (in.gcount())
        out.write(buffer, in.gcount());
  }
  
  delete[] buffer;

  return true;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question