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?
-
1Please add more information to the question. Show the code that you have already. Do you know how to read all text from a file? – 463035818_is_not_an_ai Nov 26 '20 at 10:05
-
1What did you try? Can you read a full file? What is "get" in your case? Read how to provide a [mcve]. – Costantino Grana Nov 26 '20 at 10:09
-
I want to open a text file and get half of that text – user32800 Nov 26 '20 at 10:10
-
If "half of the text of that file" may be measured in bytes, this https://stackoverflow.com/questions/50491833/how-do-you-read-n-bytes-from-a-file-and-put-them-into-a-vectoruint8-t-using-it might help. – ctenar Nov 26 '20 at 10:17
-
What do you mean by *half of the text*? The first lines? Half of each line? – Damien Nov 26 '20 at 10:17
1 Answers
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.

- 14,694
- 5
- 19
- 44