Search code examples
c++file-iofile-read

How to find number of characters in a file without traversing the contents


In a project, I have to read a file, and i have to work with the number of characters in a file, and is there a way to get number of characters without reading it character by character (otherwise i will have to read the file twice, once just to find the number of characters in it).

Is it even possible?


Solution

  • You can try this:

    FILE *fp = ... /*open as usual*/;
    fseek(fp, 0L, SEEK_END);
    size_t fileSize = ftell(fp);
    

    However, this returns the number of bytes in the file, not the number of characters. It is not the same unless the encoding is known to be one byte per character (e.g. ASCII).

    You'd need to "rewind" the file back to the beginning after you've learned the size:

    fseek(fp, 0L, SEEK_SET);