Finding the size of a file I recently learned that sometimes, when running code, the compiler(or whatever it is) ignores when there isn't enough memory for say, a string, and interacts with the string normally.

Yes, I know this is a "lucky" thing that shouldn't happen, but sometimes does.

I often find trouble when I'm trying to interact with the contents of file, as I often run out of allocated memory and I have trouble dynamically re-allocating.

To fix this, I created two functions:


fsizeof_full &lt;- returns the full size of the file(as if it were a string)
fsizeof_buffer &lt;- returns the size of the largest line in the file


So far, as I have been using these, I have not come across any problems involving segmentation faults, but I am not sure if I am just getting lucky.

Here is my code(these both have stdio.h included):

fsizeof_full

unsigned int fsizeof_full(FILE *fp) {
    unsigned int size;
    while(getc(fp) != EOF)
        ++size;
    return size;
}


fsizeof_buffer

int fsizeof_buffer(FILE *fp) {
    int buff = 0; // holds the largest size of a line
    int temp = 0; // holds the size of the current line

    int c;
    while((c = getc(fp)) != EOF) {
        ++temp;
        if(c == '\n') {
            buff = (temp &gt; buff)?(temp):(buff);
            temp = 0;
        }
    }
    return buff;


Along with the above question("So far, as I have..."), could you possibly include more thoughts about the code regarding efficiency, necessity, etc.
For the first function you can address the OS to find out for you:

unsigned long long fsizeof_full(FILE *fp) {
    struct stat size;
    fstat(fileno(fp), &amp;size);
    return size.st_size;
}


You'll need to include the following headers for it to work.

#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;


Or you can simply seek to the end of the file (with fseek(fp, 0, SEEK_END)) and use ftell

Besides that files nowadays can easily exceed 4 gigabytes which will overflow the int, both posix and windows have (differently named) variants on ftell that returns a 64 bit number.