I am trying to answer the question:
If you have a file declared "FILE *f;" the sizeof(f) function returns the size of the file.
When loading the data to the file, I notice that the size is not updated, therefore I conclude that it is False. Here the script I used:
int main()
{
FILE *f;
f = fopen("cagandoejemplos.dat", "wb");
for(int i = 0; i < 5; i++)
{
fwrite(&i,sizeof(int),1,f);
}
fclose(f);
int tam = sizeof(f);
cout << tam;
return 0;
}
However, looking at the theory I can't find an explanation that I understand why size of would not be working with the files. If I can see how to "Calculate the length of a file"
Nor did I find the answer in Kernighan and Ritchie. What is the same as here ?
So my question: while I can't use 'sizeof' to know the size of a file, why is this so?
False, returns the size of the variable
f
.That statement, as @PaperBirdMaster has told you, is false.
sizeof
is an operator that indicates the size of the type passed to it as a parameter.In the case at hand,
f
it is nothing more than a pointer to a structure used internally by the input/output library to manage access to a file. In other words... you don't have direct access to the file , so you can't use itsizeof
to solve the problem.I wouldn't trust those answers for several reasons:
If the file is binary
fseek(SEEK_END)
it is not safe. Systems have a bad habit of paging and segmenting memory. This means that a file that occupies a single bit occupies up to several KB on the disk (depending on the file system used)... which is the size of a block. Binary access in these cases may be unable to detect the end of the file since, after all, everything is bytes and they can all be valid.In fact, in the documentation you can read the following notice:
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 It is longer.
Again in the documentation you can read the following:
So, I'm sorry. The example you have chosen is going to give you problems everywhere.
Then?
Unfortunately there is no standard solution. If you start from the assumption that the file contains ASCII text, then yes, you could make use of the example you mention... but always knowing its limitations.
Another option could be to open the file with wide chars to adapt to the encoding that the file is using and read character by character keeping count (it is a slow mechanism but with small files it could be worth it).
A third possibility (if you are only interested in knowing the approximate size) is to access the properties of the file: