Pages

Getting the file size

In the previous post, as a way to have a first glimpse of the Boost Filesystem library, we wrote a rough but usable function that used boost::filesystem::file_size().

Let's going on pretending that we developed that function as answer to a client request, who now asks for an improvement, since he would like to have a better output. He could accept to be notified of an exception if really happens something unexpected (like: the unit specified on the file system does not exist), but in case the passed filename refers to a non existing object in the file system, or such an object is not a regular file (for which it has actually sense retrieving the size) he wants to be notified in a more gentle way.

Not a big issue, we just have to use a few other Boost Filesystem functions.

Here is the code for the improved function:
void fileSize2(boost::filesystem::path filename)
{
try
{
if(!boost::filesystem::exists(filename)) // 1.
{
std::cout << filename << " does not exist" << std::endl;
return;
}

if(boost::filesystem::is_directory(filename)) // 2.
{
std::cout << filename << " is a directory" << std::endl;
return;
}

if(!boost::filesystem::is_regular_file(filename)) // 3.
{
std::cout << filename << " is not a regular file" << std::endl;
return;
}

std::cout << filename << " size: "
<< boost::filesystem::file_size(filename) << std::endl; // 4.
}
catch(const boost::filesystem::filesystem_error& ex) // 5.
{
std::cout << ex.what() << std::endl;
}
}

1. Firstly we check if the passed name refers to an object in the file system. Notice that usually a Boost Filesystem functions, like exists() here, throws a filesystem_error exception if anything weird happens. Alternatively, when for any reason we don't want to (or we can't) use the try-catch structure, we could call a function overload that returns an error code.
2. Secondly, since does not make much sense to check the size of a directory, we check it using the is_directory() function.
3. Thirdly, we consider that there could be more than normal files and directories in a file system. Here we trap the case in which the passed file name is associated with "something" that in our current environment is not recognized as a "regular" file.
4. Finally we call the Boost Filesystem function to get the file size.
5. Any unexpected error from the previous calls to Boost Filesystem functions is trapped here, giving back to the user the message stored in the exception.

The code in this post is based on an example that you can find in the official boost filesystem tutorial. For more background information, you could have a look at the Boost filesystem version 3 home page.

No comments:

Post a Comment