1

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?

Maxpm
  • 24,113
  • 33
  • 111
  • 170

5 Answers5

4

std::streampos is the standard type for representing positions in character streams (including files).

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

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

Community
  • 1
  • 1
user237419
  • 8,829
  • 4
  • 31
  • 38
2

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.

janneb
  • 36,249
  • 2
  • 81
  • 97
0

If you are talking about ASCII characters, they wont have values above 127. Therefore, using unsigned char data type would suffice.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
  • 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
0

Do you want also represent "invalid index" somehow? If so, why don't just use ssize_t.

Alexander Poluektov
  • 7,844
  • 1
  • 28
  • 32