the error I'm getting here is that if statement on line 24 keeps evaluating as true and returning the file error. |
Opening a file with ios::in will fail unless the file already exists. It will not create a new file if the file is not already there.
This is extremely likely that this is what is happening for you. If the file is there, make sure you are inputting the file name properly (extension included) and make sure the file is in the correct path. Having the file in the wrong path is another common mistake.
int recsize = sizeof(name) + sizeof(int);
This does not do what you think it does. sizeof(name) will give you the size of the std::string class, which is completely meaningless for your purposes.
This line probably made sense if 'name' was a char array. But it simply does not translate to strings.
if(strlen(s.c_str()) == 0)
While this will work, it's extremely roundabout and kind of silly. You're converting the string to a char array... just so you can use a char function. Instead, you could just use the string functions (which will undoubtedly be faster). Alternatives are:
1 2 3
|
if( s.empty() ) // <- best
//
if( s.length() == 0 ) // <- still better than strlen
|
|
binfile.write(name.c_str(), 20);
|
This will only work if 'name' is at least 19 characters long. You never guarantee that. So it's possible this is accessing out of bounds memory which may lead to strange behavior and/or program crash (though it's unlikely).
You are correct that std::string should be preferred over char arrays in most instances. However... for this particular project -- where you are doing naive dumps of string data to a binary file.... this is one of the very few instances where fixed-length char arrays make the job easier.
It's clear this assignment was designed to have 'name' be no larger than 20 characters, and for it to dump a fixed-length array to the file. That is more difficult to accomplish with strings which allocate memory dynamically and can have a variable length.