18.6 — Basic file I/O

File I/O in C++ works very similarly to normal I/O (with a few minor added complexities). There are 3 basic file I/O classes in C++: ifstream (derived from istream), ofstream (derived from ostream), and fstream (derived from iostream). These classes do file input, output, and input/output respectively. To use the file I/O classes, you will need to include the fstream header.

Unlike the cout, cin, cerr, and clog streams, which are already ready for use, file streams have to be explicitly set up by the programmer. However, this is extremely simple: to open a file for reading and/or writing, simply instantiate an object of the appropriate file I/O class, with the name of the file as a parameter. Then use the insertion (<<) or extraction (>>) operator to read/write to the file. Once you are done, there are several ways to close a file: explicitly call the close() function, or just let the file I/O variable go out of scope (the file I/O class destructor will close the file for you).

File output

To do file output in the following example, we’re going to use the ofstream class. This is extremely straighforward:

If you look in your project directory, you should see a file called Sample.dat. If you open it with a text editor, you will see that it indeed contains two lines we wrote to the file.

Note that it is also possible to use the put() function to write a single character to the file.

File input

Now, we’ll take the file we wrote in the last example and read it back in from disk. Note that ifstream returns a 0 if we’ve reached the end of the file (EOF). We’ll use this fact to determine how much to read.

This produces the result:


Hmmm, that wasn’t quite what we wanted. Remember that the extraction operator deals with “formatted output”, and breaks on whitespace. In order to read in entire lines, we’ll have to use the getline() function.

This produces the result:

This is line 1
This is line 2

Buffered output

Output in C++ may be buffered. This means that anything that is output to a file stream may not be written to disk immediately. Instead, several output operations may be batched and handled together. This is done primarily for performance reasons. When a buffer is written to disk, this is called flushing the buffer. One way to cause the buffer to be flushed is to close the file -- the contents of the buffer will be flushed to disk, and then the file will be closed.

Buffering is usually not a problem, but in certain circumstance it can cause complications for the unwary. The main culprit in this case is when there is data in the buffer, and then program terminates immediately (either by crashing, or by calling exit()). In these cases, the destructors for the file stream classes are not executed, which means the files are never closed, which means the buffers are never flushed. In this case, the data in the buffer is not written to disk, and is lost forever. This is why it is always a good idea to explicitly close any open files before calling exit().

It is possible to flush the buffer manually using the ostream::flush() function or sending std::flush to the output stream. Either of these methods can be useful to ensure the contents of the buffer are written to disk immediately, just in case the program crashes.

One interesting note is that std::endl; also flushes the output stream. Consequently, overuse of std::endl (causing unnecessary buffer flushes) can have performance impacts when doing buffered I/O where flushes are expensive (such as writing to a file). For this reason, performance conscious programmers will often use ‘\n’ instead of std::endl to insert a newline into the output stream, to avoid unnecessary flushing of the buffer.

File modes

What happens if we try to write to a file that already exists? Running the output example again shows that the original file is completely overwritten each time the program is run. What if, instead, we wanted to append some more data to the end of the file? It turns out that the file stream constructors take an optional second parameter that allows you to specify information about how the file should be opened. This parameter is called mode, and the valid flags that it accepts live in the Ios class.

Ios file mode Meaning
app Opens the file in append mode
ate Seeks to the end of the file before reading/writing
binary Opens the file in binary mode (instead of text mode)
in Opens the file in read mode (default for ifstream)
out Opens the file in write mode (default for ofstream)
trunc Erases the file if it already exists

It is possible to specify multiple flags by bitwise ORing them together (using the | operator). Note that ios::in and ios::out are already defaults for the ifstream and ofstream classes respectively. If you opt to use fstream (which can do both input and output), you explicitly have to pass in ios::in and/or ios::out depending on which mode you’d like to use.

Let’s write a program that appends two more lines to the Sample.dat file we previously created:

Now if we take a look at Sample.dat (using one of the above sample programs that prints its contents, or loading it in a text editor), we will see the following:

This is line 1
This is line 2
This is line 3
This is line 4

Explicitly opening files using open()

Just like it is possible to explicitly close a file stream using close(), it’s also possible to explicitly open a file stream using open(). open() works just like the file stream constructors -- it takes a file name and an optional file mode.

For example:

18.7 -- Random file I/O
18.5 -- Stream states and input validation

87 comments to 18.6 — Basic file I/O

  • Zoran


    In the beginning of the article, the text says:
    To use the file I/O classes, you will need to include the fstream.h header.

    However, later, in examples, fstream is included, not fstream.h.
    if I include <fstream.h>, with g++ (mingw) I get:
    fatal error: fstream.h: No such file or directory

    Without ".h", everything works. So, I think that fstream.h is wrong, and it should be replaced with fstream.

  • Aaron

    How do you delete a record in a file?
    with code example please. Oh and that works with the above examples, Thanks.

  • SimonJoel

    Hello Alex,
    This is the first time I try to use ifstream, read numbers from a file and sum them up, but the program always missing the first number. also the sum is not right. please take a look, thanks;

    the file I use is call sourcenum.txt, and it output individually right except for the first number, I have the numbers : 18 19 18.5 13.5 14 16 19.5 20 200 12 18.5 17.5 in the file.

    • Alex

      This is the perfect kind of thing to use a debugger for. Step through each line of code line by line and watch what it reads in from the file and what it does with those values.

    • SimonJoel

      Thanks Alex, figured it out, the cout should place before the sourcenum>>num, that is why the program keep skip printing the first element.
      Also, it seems sourcenum.good() will return false if the last element is right after the eof, in windows notes editor, I fix this by adding a space after the last element so the last number is not follow immediately by eof, it all work fine now.

  • Joel

    Hi Alex,

    Great site! I’m really enjoying learning about C++. I thought I’d try to write a little example for myself where I open an existing file and append values to it. Since you said I could combine flags, I thought I’d also add std::ios::nocreate. Something like this:

    This does not compile. The compiler complains saying "error: no member named ‘nocreate’ in ‘std::__1::basic_ios<char>’." Googling this error, it seems like maybe nocreate is no longer part of the standard library. If you can confirm this, then I guess this page should be updated to reflect that. 🙂

    Let me know what you think!

    • Alex

      I think I made a mistake. std::ios::nocreate and std::ios::noreplace are not officially part of the C++ standard, so not all compilers support them. I’ve removed them from the table.

      If you want to check if a file exists, you can try opening it with an ifstream first (or an fstream using std::ios::in).

  • Alex

    There isn’t really a more compact way to do it, but you could read the file into a char array instead of a std::string if you wanted. You’d have to watch out for overflowing the array when you read from the file, and for memory leaks (if using a dynamic array). I wouldn’t necessary recommend it unless performance is really critical in this section of code.

  • Elruin

    I’m trying to get fileread part of my program to separate function. The problem is I have to get my filecontent as const char*. Sofar i’ve come only with this solution:

    to this:

    does not look much better =(

    • Alex

      Why do you need your file content as const char *? If you have a std::string, you can access the underlying const char* by using member function c_str(), like this:

      • Elruin

        That’s what i used…

        I need char * for glShaderSource() functuion.
        I just thought that there is more compact way to do this. Like not using std::string at all.

  • Leon

    I have a question. I have created a program where you can read from a file as well as write to it. I wrote something into the file (it didn’t exist before), and it seemed to work. I then read from the file and everything i input appeared on the screen. however, when i look on the directory for the file that was created, it is nowhere to be seen. apparently the file exists because i can read and write to it, but i don’t see it on my directory. I am using a mac, if that information is worth anything.

    • Alex

      I agree, the file must exist. But where it went? I have no idea. Maybe give it a unique name and then do a filename search for it across your entire hard drive?

      • Leon

        i searched for it, and the file was created in a different area than where the file is saved. i have my file saved in a folder for assignments, but when i searched for the file using spotlight, it said the file was located in my user directory. so it looked something like this "user > personnel.dat". i moved the file over to the same directory as the project, but now when i try to read from the file it says the file doesn’t exist.

        • Alex

          Sounds like maybe one of the code::blocks settings is set to your personal directory instead of the executable directory. Not sure which one though. See for more info.

  • Ryan

    In the first example, I see "if (!outf)…". I am a little confused by this. This seems to be trying to access the object outf directly, rather than calling a function like "if(outf.is_open())". Is this an operator overload for the "!" operator? Is this overloaded to make it behave more like C-style file IO? I don’t understand how its possible to access an object directly like that…

    • Alex

      Yes, if you look at a reference for ofstream (e.g. this one) you’ll see that although ofstream doesn’t contain an overloaded operator!, it does contain a overloaded conversion to bool, which is being invoked here. That conversion to bool is a synonym for (! So we’re essentially saying if (!!, which is the same thing as if (, which in English means “if an error has occurred …”.

  • source bumber

    How can I append a line to an existing file, but NOT at the end of the file? I mean, with your example, I’d like to see:
    This is line 1
    This is line 3
    This is line 2

  • Nyap

    I just spent the past several hours confused about this file i/o until I realised - I’M MIXING UP INPUT AND OUTPUT LOL


  • Vlad

    Hello Alex

    Suppose you have a loop outputting x and y variables for a gnuplot .dat file. Is the process going to be buffered (automagically) or not? If I were a harddisk I wouldn’t see one single benefit in writing char by char (or group chars) to a file, or a user waiting for 1e5 data entries times ~2~3ms (or however much is a HD access time)… But I’d like to be sure about this.

    As a corollary, is there some additional setting that allows us to change the buffer?

  • Nuno

    Hello. When compiling and running your code with Visual Studio 2015 and I’m getting the following output:

    ´╗┐This is Line 1
    This is Line 2

    Do you know where that weird character in the beginning is coming from? I created the file from scratch on notepad and saved is as Sample.dat. The code is literally copy+paste from yours. Can you help? Thanks.

    • Alex

      When you say you created the file from scratch on notepad, you mean you typed “This is line 1” etc… into the file using notepad?

      If so, it may have been saved in some variant of unicode format, and this is a byte-order mark that is used to indicate what format it is. If so, your console probably doesn’t know how to print this character, so it’s picking a placeholder symbol.

  • AKG

    Referring to your comment:

    "performance conscious programmers will often use ‘\n’ instead of std::endl to insert a newline into the output stream, to avoid unnecessary flushing of the buffer"

    As I know, stream stdout is line-bufferred and so using ‘\n’ will also flush the output.

    • Alex

      There seems to be a lot of confusion on this point, largely due to how std::cout interacts with the underlying C streams. The behavior of std::cout can also be different depending on what it’s connected to. As best I can tell, there’s no requirement that std::cout be buffered or unbuffered, or that ‘\n’ flush anything. But in most implementations, std::cout probably does flush on ‘\n’ when connected to a console.

  • Ola Sh

    Hello Alex,

    Thanks for your tutorials. Is it possible to edit a file in c++, like deleting the last input into a file or any other section of the file? Thanks.

    • Alex

      Yes, you can alter files in C++.

      The easiest way to do this (for files that aren’t huge) is to read in the entire file, make your alternations in memory, and then overwrite the contents of the file with the contents in memory.

  • saad haider

    Please HELP  
    I need to read this data from a file :

    12,alex hales,23,41,12
    23,brandon mc,12,123,41

    I need to store them in
    roll number, name ,quiz1,quiz2,final
    Please HELP

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter