For example, there is a 1 GB file.

How to get a piece of data somewhere in the middle without reading it completely?

  • @KoVadim already answered, and the answer is accepted, but still ... What would you like to receive? Which file (text, binary), sorted or not, how to determine the desired site? Because all sorts of fseek require either ftell with preliminary reading, or the calculation of the right place, taking into account the file structure. - alexlz
  • file binary or text is not important. I need to find data in it at the specified size from the beginning of the file, for example 12 bytes and 24 bytes in length from the beginning of the desired data. - perfect
  • The difference is that in a text file you can start reading in an arbitrary position, find a line break, and you will get the beginning of the next one. In the binary option is not excluded that the beginning of the block can not be found. Or maybe the other way around is easier. So the situation is the same - the source data is small. - alexlz 3:38 pm
  • Let's consider two options. Let's accept the @KoVadim option as an option with a text file. Let someone write (maybe even you will do it) an option with a binary file (the condition remains the same). - perfect
  • @perfect, for fseek() (C ++ seekg() ) there is no difference between text files and binary files. There is no nix in the world *. These files only in the programmer’s head differ in some way. In Windows, indeed, there are differences at the level of data conversion when reading and writing. When reading a text file, the Ctrl-Z character is perceived as the end of the file, and the sequence of 2 characters "\r\n" is replaced with one '\n' . When writing a text file, each character '\n' is replaced with the sequence "\r\n" . - avp

1 answer 1

Use family functions *seek . If you are using the old, generic way to read files ( fopen , 'fread`), then use the fseek function. This function receives three parameters — the first — the file descriptor, the third — the “rewind” method — from the beginning, from the current position, or from the end. And the second parameter indicates how many bytes to "rewind". Also paired to her function ftell , which returns the current position.

If you use work through stream (fstream), then the seekg function is needed .

  • is it from the standard c ++ library? - perfect
  • Yes. More standard is nowhere :) - KoVadim