#Better function signature?

21 messages · Page 1 of 1 (latest)

dense grove
#

I have a function that loads a file. From this file it has to a get a number and return it. The way I currently do it is to return a bool for the status of the operation (because file opening, reading, etc.. can fail) and get the number as a parameter by reference. It works, but I think it's ugly and doesn't do the name of the function justice. Would there be a better way where I return the int and still convey if the opening/reading of the file failed somehow?

bool get_number_of(const char* file_name, const unsigned size_of, unsigned& number)
{
    std::ifstream file(file_name, std::ios::binary|std::ios::in);

    // try to open file
    if(!file.is_open())
        return false;

    if(file.tellg() > 0)
    {
        file.seekg(0, std::ios::end);

        number = file.tellg() / sizeof(size_of);
    }
    else
        number = 0;

    file.close();

    return file.good();
}
oak windBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

dense grove
#

Also before anyone says anything - this a part of a homework and I'm quite limited in what I can use. I'm not allowed to use the C++17 filesystem, nor any "modern" stl structures.

vast hound
#

exceptions

#

you also really don't need to explicitly close a file

#

the destructor of the fstream takes care of that

#

i'm not exactly sure what you mean by "get a number from it"

#

it seems you're trying to get the file size?

dense grove
#

uhh no, the file contains serialized structs and this way I calculate the number of them inside the file.

#

So the only real way is exceptions? I would've like to avoid them for the purpose of the homework, but if it's the only way

#

size_of is the size of the struct

vast hound
#

well, you can return a struct with a bool and the result, or an optional, or smth

#

there are many ways to handle errors ^^

vast hound
#

just be advised that this way of getting the size of a file is technically not a good idea

#

it's just what most people will tell you to do

#

but it's technically non-portable

dense grove
#

yeah I know. but like I said above i'm not allowed to use std::filesystem::exists()

timid sparrow
#

are you allowed to use std::optional? if not you could do it the way the person above me suggested, with a struct that has two variables, one that is a boolean that tells you if the function has executed correctly and one that contains the actual result

#

but imo std::optional is the best since it's so commonly used

tardy sluice
#

std::expected