简体   繁体   中英

c++ function overloading, making fwrite/fread act like PHP versions

I'm used to the PHP fwrite/fread parameter orders, and i want to make them the same in C++ too.

I want it to work with char and string types, and also any data type i put in it (only if length is defined).

I am total noob on c++, this is what i made so far: Edit: fixed the std::string &buf

size_t fwrite(FILE *fp, const std::string &buf, const size_t len = SIZE_MAX){
    if(len == SIZE_MAX){
        return fwrite(buf.c_str(), 1, buf.length(), fp);
    }else{
        return fwrite(buf.c_str(), 1, len, fp);
    }
}

size_t fwrite(FILE *fp, const void *buf, const size_t len = SIZE_MAX){
    if(len == SIZE_MAX){
        return fwrite((const char *)buf, 1, strlen((const char *)buf), fp);
    }else{
        return fwrite(buf, 1, len, fp);
    }
}

Should this work just fine? And how should this be done if i wanted to do it the absolutely best possible way?

If you want to write to a file in the best possible way, you should use std::iostreams. Dealing with the length of the buffer manually is a recipe for problems.

Also, the top overload should take a const std::string&, not const std::string.

However, I don't see any actual bugs.

fwrite / fread don't really work very well with objects; so as @DeadMG says you'd be better of with streams.

something like:

cout << str << endl;

It's a much more OO way of doing things - you can overload the operators within the objects to handle the different requirements of each individual object.

This isn't the right sort of overloading of functions IMO. If anything these functions should be methods within the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM