Malcolm said:
unsigned long harddisksize(void)
{
unsigned long answer = 0;
do
{
FILE *fp = fopen( tmpnam(0), "wb"));
if(!fp(break));
if(fputc('x', fp) == EOF)
break;
answer++;
}
while(fclose(fp) == 0);
printf("You had %lu bytes of disk space\n", answer);
return answer;
}
}
I presume this was meant as a joke. It attempts to fill the file
system with 1-byte files and reports how many it was able to create.
Apart from the folly of filling the disk to determine how big it is
(and not freeing the allocated disk space; the use of the past tense
in the printed message acknowledges this), tmpnam() can't necessarily
return more than TMP_MAX unique file names, and TMP_MAX is only
required to be at least 25. Creating a 1-byte file will almost
certainly use more than 1 byte of disk space. Even assuming each file
occupies only 1 byte, and ignoring the TMP_MAX issue, the amount of
free disk space is likely to exceed ULONG_MAX; if so, the answer
returned will be the actual amount modulo (ULONG_MAX+1). Finally, the
function should either print the result or return it; doing both is
silly.
I'd put the "while" on the same line as the closing brace; on first
reading I thought it was an empty while loop rather than a do-while
loop.
And of course typical systems have multiple disjoint file systems;
your function has no way to control which one is used (you're going to
get whichever one tmpnam() happens to use).
If I were really going to do this in this way, I'd probably see how
many bytes I can write to a single file. Depending on the system, I'd
likely exceed my quota before running out of space and/or seriously
interfere with other users.
This is one of those problems for which there are no decent portable
solutions, but many perfectly good system-specific solutions.