Enlarged streampos

I am trying to do something like this:

for (std::streampos Position = 0; Position < 123; Position++) { // Use Position to access something... } 

However, it seems that std::streampos does not have an overloaded operator++ .

Attempting to use Position = (Position + 1) results in the following error:

 ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: 

Is there any workaround for this, or should I rely on a long unsigned int big enough for files?

+5
source share
4 answers

Try std::streamoff , which represents the offset in the stream. It supports both pre-and post increment / decment statements.

The main type is an implementation, defined, but must be able to be sequentially converted to both streamsize and fpos ( therefore, also to streampos )

Edit Maxpm comment: you can apply streamoff anywhere, be it ios::beg or arbitary streampos . Apply it to ios::beg and it behaves like regular streampos . Apply it to streampos and you get streampos+streamoff .

+5
source

Use += :

 for (std::streampos Position = 0; Position < 123; Position += 1) 

+ does not work, because operator + actually defined for streampos and steamoff , not int .

This means that there are two implicit conversions that are equally good: either your 1 can be converted to streamoff (which is probably a typedef for unsigned long ). Or streampos implicitly converted to streamoff , which then added 1 .

+4
source

std::streampos not a numeric type, although it does support conversion from and to numeric types. If you want to do arithmetic at a position, you need to use std::streamoff (and specify an argument when calling seek).

Also, do not forget that you cannot search for an arbitrary position in a file if it has not been opened in binary mode and is saturated with the "C" locale.

+3
source

I came across this link, studying how I can subtract from the std::streampos : https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=187599

The proposed solution uses a given operator overload operator+() or operator-() which work pretty well for me.

 Position.operator+(increment_val); Position.operator-(decrement_val); // alternative 

PS It may be better to use operator+() than operator-() to avoid any problems associated with the change of sign

0
source

Source: https://habr.com/ru/post/1346070/


All Articles