开发者

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 th开发者_如何学Pythone 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜