HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Getting the length of a file in characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thefilelengthgettingcharacters

Problem

Here's my function for getting the length of a file, in characters:

unsigned int GetFileLength(std::string FileName)
{
std::ifstream InFile(FileName.c_str());
unsigned int FileLength = 0;
while (InFile.get() != EOF) FileLength++; 
InFile.close();
return FileLength;
}


How can this be improved?

Solution

I dislike seeking, so here's my non-seeking approach.

#include 
#include 
#include 
#include 
#include 

off_t GetFileLength(std::string const& filename)
{
    struct stat st;
    if (stat(filename.c_str(), &st) == -1)
        throw std::runtime_error(std::strerror(errno));
    return st.st_size;
}

Code Snippets

#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <stdexcept>
#include <string>

off_t GetFileLength(std::string const& filename)
{
    struct stat st;
    if (stat(filename.c_str(), &st) == -1)
        throw std::runtime_error(std::strerror(errno));
    return st.st_size;
}

Context

StackExchange Code Review Q#1405, answer score: 6

Revisions (0)

No revisions yet.