I would like to translate the following C code to C++.
FILE *fp = NULL;
fp = fopen("./filename", "r");
int i = 0;
fscanf(fp, "%d\n", &i);
uint16_t j = (uint16_t) i;
This is what I came up with this:
ifstream file;
string filename = "./filename";
file.open(filename.c_str(), ios::in);
errno = 0;
if (file.fail()) {
int tmp = errno;
std::cout << file.c_str () << " not found: strerror(" << tmp << "): " << strerror(tmp) );
}
int i = 0;
file >> i >> std::endl;
uint16_t j = (uint16_t) i;
I would like to know whether the syntax is correct or improvable and more importantly whether it’s safe against all kinds of inputs.
Note if you do not have C++11 then you will need to use
c_str()to open the file, but the string method is prefered.EDIT: fstream close themselves, there is no need to close it yourself, the functionality is there incase you do have to do that however it is far better to rely on RAII semantics:
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
RAII dictates that you should open the file on construction and it will close on destructions, this ensures that there isn’t any invalid (exclude EOF, file not found…) fstream object preventing bugs. RAII is a fundamental construct in C++ and should be used where ever resources are concerned.
The docs for the fstream destructors is here:
http://en.cppreference.com/w/cpp/io/basic_fstream