Lemme share an insight from where I work... "the real word" if you will... XD
Our C++ code base uses lots of the scanf and printf variants for parsing data. Over time, these calls started crashing the program. Basically, we have stuff like this:
Code: Select all
sscanf(dataBuffer, "%4d%2d%2d", &year, &month, &day);
The problem with this kind of code is that it is not type-safe. It makes general assumptions about the parameters based on the format string; scanf does not really
know that year/month/day are integers. It just assumes you were smart enough to give it the right stuff. In the case of our code, if the incoming data is malformed or incomplete (or some lazy engineer put the wrong number of parameters), data was exiting the program's memory boundaries and blowing stuff up. (Michael Bay programming! WOOOOO!)
I now much prefer doing this.
Code: Select all
std::stringstream ss;
ss << formattedYear << ' ' << formattedMonth << ' ' << formattedDay;
ss >> year >> month >> day;
Sure, it takes a little bit more setup (depending on how the data is coming in), but this prevents all the memory-stomping that was going on in the earlier code snippet. So, coming back to the topic's question: should you use cstdio or fstream? Sometimes, it doesn't matter. One thing I like about C# is that file operations have mostly been reduced to single line commands: File.ReadAllBytes opens a file, loads the entire file into a byte array, and closes the file. I've gotten into that habit in C++ (assuming the file is not ridiculously huge): open the file, load the entire file into a char array, close the file, and perform all operations on the array. So, in that respect, it really doesn't matter a whole lot whether I use fopen of ifstream. (I even ended up using fopen in some of my Android code because STL was not available/stable yet.)
However...
I think in the long run, it is better to use fstream. Your I/O will be type-safe and have a lower chance of blowing up in your face. Especially if you still plan on reading directly from the stream (instead of loading it into a char array first), you will have the ability to read out words/lines at a time, use <iomanip>, etc.