stdio
(or cstdio
) is a library inherited from C while fstream
is an exclusive C ++ library. Differences? a few (I'll list some):
-
stdio
is inherited from C whereas fstream
is own C ++
- the C ++ own input libraries allow the abstract and homogeneous use of its functionality
- C ++ libraries are extensible
- C ++ own libraries can use
iomanip
stdio
is inherited from C whereas fstream
is own C ++
In stdio
you will find a collection of functions (not classes) designed to interact with the input / output, while in fstream
what predominate are the classes (for something is a C ++ own library).
C ++ inbound output libraries allow the abstract and homogeneous use of its functionality
Being based on classes, and thanks to the fact that these classes have inheritance, it is possible to implement exit mechanisms independent of the origin or final destination of the data:
// ¿el destino es un fichero? ¿sera la consola? ¿quizas una impresora?
void PrintDatos(std::ostream& out)
{
out << "abcdefg";
}
This feature helps to reuse code. Okay, someone will tell me that with stdio
can also be done:
fprintf(stdout,"abcdef");
The difference is, in this case, that making use of this feature with stdio
will prevent us from using practically half of the functionality offered by this library since the functions that do not support as an input parameter a FILE*
will not be able to be used in this context. The latter contrasts with the C ++ libraries that do not lose functionality.
C ++ libraries are extensible
That fstream
is a C ++ own library means that it has been designed with C ++ characteristics in mind, which implies that, for example, its functionality is extensible through our own overloads:
struct Test
{
int valor;
char caracter;
Test(int v, char c)
: valor(v), caracter(c)
{ }
};
std::ostream& operator<<(std::ostream& out, Test const& test)
{
return out << test.valor << test.caracter;
}
int main()
{
std::vector<Test> lista { {1,'a'},{2,'b'},{3,'c'},{4,'d'} };
for( auto& test : lista )
std::cout << test;
}
A similar design would be unthinkable with stdio
or, at least, it would be more expensive to program and less natural, which would generate more complicated code to read.
C ++ libraries can use iomanip
Another interesting feature of the C ++ own output entry is that it is possible to use the iomanip
library to configure how the information is to be downloaded. This feature alone does not contribute much, but when combined with the above characteristics allows to obtain quite elegant solutions:
std::cout << std::setw(10) << std::setfill('#') << 45;
Conclusion
stdio
basically exists because C ++ was in the beginning a kind of C slightly vitamin. According to C ++ it was leaving its predecessor has been acquiring bookstores for their own interests.
Currently stdio
serves more as a compatibility library to be able to bring C ++ code C. If you are making new code it is preferable to use the C ++ own libraries.