If you have a file declared "FILE * f;" the sizeof (f) function returns the size of the file.
That statement, as @PaperBirdMaster has told you, is false. sizeof
is an operator that indicates the size of the type that is passed to it as a parameter.
In the case that concerns us, f
is not more than a pointer to a structure used internally by the input / output library to manage access to a file. In other words ... you do not have direct access to the file , then you can not use sizeof
to solve the problem.
If I can see how to "Calculate the length of a file"
I would not trust those answers for several reasons:
-
If the file is binary fseek(SEEK_END)
is not safe. Systems have a bad habit of paging and segmenting memory. This makes a file that occupies a single bit occupy up to several KB on the disk (depends on the file system used) ... which is the size of a block. The binary access in these cases may be unable to detect the end of the file since, after all, all are bytes and all can be valid.
In fact in the documentation you can read the following notice:
Binary streams are not required to support SEEK_END, in particular if additional null bytes are output.
-
If the file is text and does not use ASCII encoding, there will be characters that occupy more than 1 byte ... in this case, going to the end of the file and measuring the offset will give an incorrect result ... it will tell you that the file is longer.
Again in the documentation you can read the following:
If the stream is wide-oriented, the restrictions of both text and binary streams apply (result of ftell is allowed with SEEK_SET and zero offset is allowed from SEEK_SET and SEEK_CUR, but not SEEK_END).
So I'm sorry. The example you have chosen will give you problems everywhere.
Then?
Unfortunately there is no standard solution. If you assume that the file contains ASCII text then you could use the example you mentioned ... but always knowing its limitations.
Another option could be to open the file with wide chars to adapt to the encoding that is using the file and read character to character keeping the account (it is a slow mechanism but with small files could be worth ).
A third possibility (if you only want to know the approximate size) is to access the properties of the file:
size_t TamFichero(std::string const& nombre)
{
stat stat_buf;
int rc = stat(nombre.c_str(), &stat_buf);
if (rc == 0)
return stat_buf.st_size;
return -1;
}