fscanf c++ equivalent


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.


int read_int(const std::string file_name) { std::ifstream file(file_name); //the file will close itself on destruction std::uint16_t i; //extract type, don't worry about what it is it will either compile or not if(!(file >> i)) { //Catch failure //or however you wish to deal with it. throw std::runtime_error("can't read file"); } return i; } int main() { try{ std::uint16_t i=read_int("./filepath"); //do with i... } catch(const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }

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:

<a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="nofollow">http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization</a>

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:

<a href="http://en.cppreference.com/w/cpp/io/basic_fstream" rel="nofollow">http://en.cppreference.com/w/cpp/io/basic_fstream</a>


destructs the basic_fstream and the associated buffer, closes the file



The exact equivalent would be:

std::ifstream fs( "./filename" ); int i = 0; fs >> i >> std::ws; uint16_t j = i;

Whether this is what you really want is another question: the use of a "\n" in the format string for fscanf suggests (to me, at least) that you really want to read a single '\n', and not arbitrary white space; what the "\n" means in fscanf, however, is to skip up to the next non-whitespace. (In the case of interactive input, this can be a real problem, since you won't return from your scanf—or my replacement above—until you've encountered a non-white space character or end of file. For input from a file, it may not be an issue.)

When reading line oriented input, the classical solution is to use std::getline, and then an std::istringstream to parse it.


  • Returning a reference from a function in c++
  • Why wont my program execute the second catch block, when the error exists?
  • How can I open a file for reading & writing, creating it if it does not exist, without truncatin
  • how to catch a general exception and show its derived what()
  • Uploader produces errors regarding the column in which it should store the path
  • XSLT removing arbitrary duplicate sibling elements
  • find a file in a nested directory structure
  • passing parameter to server in ExtJs
  • Insert Columns between columns in excel
  • Different builds of turn-based Game Center game can’t see each other’s matches
  • twisted.internet.error.ConnectError when run scrapy spider
  • Extjs, handling success or failure when doing a standard submit in a form
  • How to implement simple validation in Scala
  • What does @synthesize variable = _variable really do? Is it very helpful?
  • SSH in Bash Script Messing Up File Read
  • Print character to a certain point on console in Python?
  • Many to Many in Linq using Dapper
  • Ionic storage “get” returns null only on the second call within method
  • How can I prevent the need to copy strings passed to a avr-gcc C++ constructor?
  • multidatatrigger with multibinding in ControlTemplate.Triggers
  • Cloud Code function running twice
  • NUnit 3.0 TestCase const custom object arguments
  • Combining two different ActiveRecord collections into one
  • C: Incompatible pointer type initializing
  • Thread safety of a fluent like class using clone() and non final fields
  • Groovy: Unexpected token “:”
  • Converting a WriteableBitmap image ToArray in UWP
  • Reading JSON from a file using C++ REST SDK (Casablanca)
  • Why value captured by reference in lambda is broken? [duplicate]
  • Read text file and split every line in MSBuild
  • AES padding and writing the ciphertext to a disk file
  • VS2008 Enable C++ Exception with SEH
  • javascript inside java/jsp code
  • Google cloud sdk not working when python points python3
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • SQL merge duplicate rows and join values that are different
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Qt: Run a script BEFORE make
  • LevelDB C iterator
  • Can't mass-assign protected attributes when import data from csv file