I just can not understand why, if I want to know the length of the file ~ 3GB in bytes like this:

FILE * f; errno_t err = fopen_s(&f, "a.iso", "rb"); if (f == NULL) { return 0; } unsigned long int size = filelength(fileno(f)); cout << size << endl; 

then it gives me the maximum possible number for the type unsigned long int 4 294 967 295. With small files, everything is fine (although I use int there). The filelength function filelength declared in <io.h> .

Tell me, please, what is wrong here.

  • and how is the filelength function declared? - Vlad from Moscow
  • it’s standard from here #include <io.h> - Alex

2 answers 2

Well, if the file is big :), then for this there is, for example, _filelengthi64 (more _filelengthi64 here ).

  • Thank you filelengthi64 - that was what was needed) - Alex
  • Well, if you like it - mark the answer as accepted :) - Harry
  • Similarly, I have already marked it, litter just until I got comfortable with it - Alex

The filelength function returns the length of the file in bytes. A return value of -1L indicates an error and errno is set to EBADF to indicate an invalid file handle.

It must be remembered that the returned variable is of type long.

Signed long is up to 2 GB. If the file size is larger, an overflow would occur, but the function handles it and reports an error, returning -1.

Yes, that's true if I write long int size = filelength (fileno (f)); That returns -1L, but I take unsigned long int and here the max value is 4,294,967,295, here it is for some reason displayed even though the file itself is smaller, ~ 3gb

Because functions don't care what type you assign the result to. It always returns long, which means -1 for too large files. When you assign it to unsigned long, you get an unsigned number with the same set of bits. All single bits in a sign number mean -1, and in unsigned - maximum.

  • Yes, it is if I am writing - Alex
  • Yes, that's true if I write long int size = filelength (fileno (f)); That returns -1L, but I take unsigned long int and here the max value is 4,294,967,295, here it is for some reason displayed even though the file itself is smaller, ~ 3gb - Alex
  • @Alex, the bit value 4,294,967,295 in 32-bit unsigned is the same as -1 in 32-bit signed. Look for another 64-bit feature. - avp
  • @Alex, updated the answer. - Qwertiy
  • Thanks for the clear explanation - Alex