What is the typical type used to store the index of a character in a file? I'm currently using long unsigned int, but does this make sense? Should I use std::size_t instead, or does that make even less sense?
- 22,560
- 30
- 103
- 164
-
what is index of a character? – Shamim Hafiz - MSFT Mar 28 '11 at 12:23
-
@Gunner The `n`th character. So if I had a file with the alphabet, `G` would have an index of 6. – Maxpm Mar 28 '11 at 12:24
5 Answers
std::streampos is the standard type for representing positions in character streams (including files).
- 242,813
- 27
- 432
- 630
you are probably safe with both; basically you want to be able to store the max_file_size value;
the size in bytes of a file is defined as a long in struct stat; on 64bit platform size_t is probably always defined as a 64 bit number, on 32bit as a 32bit number, etc; unless you're using weird compilers.
check out a size_t related post
I would go for the long. std::size is language specific and I tend to use an operation-specific type here. but again, I see no problem with using std::size_t as well
- 1
- 1
- 8,363
- 4
- 29
- 38
As Mike Seymor says, if you work with C++ io streams, std::streampos is the standard type for representing a file position. See
http://www.cplusplus.com/reference/iostream/streampos/
Note that std::size_t might not be correct. For instance, on a 32-bit system, std::size_t will be a 32-bit unsigned integer, whereas the system might well support files larger than 2^32 bytes = 4 GB.
FWIW, in the POSIX world, there is a (signed) integer type off_t which is used for representing file sizes and offsets. With various macros (e.g. _FILE_OFFSET_BITS=64 on Linux) one can redefine off_t to become a 64-bit type.
- 34,114
- 2
- 76
- 93
If you are talking about ASCII characters, they wont have values above 127. Therefore, using unsigned char data type would suffice.
- 20,466
- 38
- 110
- 169
-
I'm not talking about ASCII characters; I'm talking about any given character's position in a file. – Maxpm Mar 28 '11 at 13:36
Do you want also represent "invalid index" somehow? If so, why don't just use ssize_t.
- 7,500
- 1
- 26
- 32