If I want to make a file to save my inputs in it, like what the user enters.
How do I create this file, edit it, delete from it.
I was told to use <fstream.h> but I dont know how!
So can you give me the codes please.

Thank you

First, unless you are using a really old version of the C++ library - by which I mean pre- ANSI / ISO standard C++ - the names of the header file is just fstream - the standard C++ library headers now have no .h suffix. Note that the C++ standard was published in 1998 so most compilers have had time to catch up to the standard.

fstream is part of the C++ IOStream library so you may also require certain other headers as well such as iostream and/or iomanip.

Now I cannot provide you with "the codes" because "the codes" do not exist. How you wish to use the IOStream library features is up to you and presumably depends on your application's requirements.

I am going to have to presume that you understand the basics of creating an application using C++ - editing the code, compiling it, linking it with libraries an other modules, debugging the executable. I also assume you are familiar with the concept of including header files to gain declarations and definitions for items external to the module being compiled - such as file I/O stream facilities.

Sorry but I am not going to be able give you a complete reference - that would take too long - I suggest you obtain a good standard C++ library reference - such as "The Standard C++ Library a Tutorial and Reference" by Nicolai M. Josuttis - which I use all the time. The chapter on IOStreams is 100 pages long - although this covers more than just the file access aspects of IOStreams.

Now to operate on a file you use std::ifstream objects for reading (input) and an std::ofstream objects for writing (output). These are the types for char sized characters. They have equivalents for wide character type (wchar_t) characters - std::wifstream and std::wofstream. Note that the std:: prefix is used because, like practically all C++ standard library entities, these types are defined in the std namespace. I am not going to go into namespaces here, if you do not understand them then refer to a good, modern, C++ language reference.

Before using a file you must open it - for reading, writing or both. You can create a new file (useful in this case), or open an existing file (useful for reading and writing an existing file). A file can be opened either when a file stream object is created - using one of their constructors - or later by calling an open member function.

One of the things you wish to do is create a file - so presumably you wish to write to it in this case. You can do this like so:

       #include <fstream>


       // In some function:

         std::ofstream outFile("myfile.txt" );

         if ( ! outFile )
         // Open failed - take error handling action.

This opens the file myfile.txt for writing, creating the file if necessary and emptying any previous contents. This is the default open mode for std::ofstream. The default open mode for std::ifstream is open an existing file for reading. This is the only way std::ostream and std::ifstream differ. Both allow these default to be overridden by the use of a second parameter to their constructors (or open member functions):

       #include <fstream>


       // In some function:

         std::ofstream outFile;
         , std::ios::out | std::ios::app

         if ( ! outFile.is_open() )
         // Open failed - take error handling action.

Here I have used the open and is_open member functions instead of opening the file in the constructor and testing the stream directly. They achieve the same thing. In this case I have explicitly stated the open mode for the file - std::ios::out | std::ios::app - out for writing and app for append - open for writing, appending to existing content. Other mode flags are in (input - reading), trunc (truncate - empties existing contents) and ate (at end - position at file end after opening - like append for reading). All are in the std::ios namespace (in fact ios is a class - or more precisely a typedef for the char specialisation of the basic_ios class template).

To open a file for reading and writing you can combine std::ios::out with std::ios::in when opening the file.

Note that the filename is a char * C style string - not a C++ std::string - so if your file name is a std::string then you need to use its c_str member function convert it to a C string before passing to a file stream constructor or open member function.

A stream can be closed by calling the close member function. It will also be closed when the stream object is destroyed (i.e. when its destructor gets called). You should close a stream when done with it to flush buffers and release resources and file locks.

There are many ways to write to a stream - you can use the stream insertion operator (<<) for example, if the types you are writing to the stream support one:

       outFile << "Some Text.";
       outFile << " More text, ending the line \n";
       int number(1234);
       outFile << "A number: " << number << "\n";

Or you can the output member functions for streams:

       outFile.put( 'c' ); // write a single character
       std::string buffer("some text" );

// Write a number of characters from a char * buffer:
// Note here we write the whole of a std::string, converting it
// to a char * C string using c_str(). The terminating zero of the
// C string is not used.
       outFile.write( buffer.c_str(), buffer.size() );

       outFile.flush(); // flush any unwritten data to the file.

Editing and deleting - which is a sub-case of editing - a file directly is usually not a good idea. A better approach is to read the whole file into memory, let the user manipulate the memory image and then write the whole file out to disk when they are done or when they request it or even when you detect they have not done so for a while and might loose their work. To read a file use a std::ifstream and use one of the file input functions: get, getline, read, readsome.

It is usually a good idea to perform something like the following stages when writing a new version of the file:

       Write the new file to some temporary file name.

       Delete any old backup file(s).

       Rename the existing file to a backup file name - a common
       convention is to prefix the name with a tilde (~).

       Rename the temporarily named new file version to the proper
       name for the file.

The idea is that you always leave the existing data as is until you are sure you have the new data saved. Any errors at least leave you with the old data - even if it is in a renamed file.

You might have to add some additional cleanup code to cope with left over temporary files on failures.

How you rename and delete files depends on the system you are using. The C standard library (also part of the C++ standard library) has a rename function in stdio.h (or cstdio for C++). UN*X uses the unlink function for deleting files and the Microsoft Visual C++ runtime library has an equivalent function called _unlink (although sometimes you can use it as unlink - depending on the compiler options I think).

This is a very brief introduction and you will have to look for full reference material - note that I am referring to the Josuttis C++ Standard Library book and The C++ Standard book to write this - I do not keep all the niggling details in my head. Nor do I have the time (on Xmas day especially!) to copy out pages and pages of reference material to you and create examples for you to use.

However I do hope this gets you going. I have just entered:

       C++ IOStreams

into Google and found this site: http://www.cplusplus.com and have added it to my favourites for future reference. Of particular interest for you is their IOStreams reference page: http://www.cplusplus.com/ref/iostream/ - hope this helps.  


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.


My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.


©2017 About.com. All rights reserved.