views:

75

answers:

2

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?

+2  A: 

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.

DeadMG
Newbie
Richard Harrison
ah, was thinking about that, thanks!
Newbie
It's like a pointer, except the compiler handles all the arithmetic.
DeadMG
+1  A: 

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.

Richard Harrison