1

I want to open a file and get only half of the text of that file, I do not want to get everything I want to open a file and get half the text How is it done?

user32800
  • 11
  • 1

1 Answers1

2

That is not complicated. The important point is that you first need to get the file size.

There are many examples here on SO how to get the file size. See for example here

Then, you divide the file size by 2. The result is the number of bytes you want to read.

With a simple for loop, you can then read character by character the requested number of times. That you can store in a std::vector or any "container",

If you are more advanced, then you would usestd::copy_n together with an std::istreambuf_iterator and a std::backinserter for the std::vector. But in the beginning a for-loop with a push_back function would be sufficient.

If your question is related to reading lines, and then reading only half the lines of the file, then the approach is different. You need to read the whole file and count the line breaks '\n'. Then you can divide by 2 and use std::getline in your for loop.

With that information it should be easily possible to write the code.

A M
  • 14,694
  • 5
  • 19
  • 44