Pages

Monday, December 6, 2010

File Modes - Reading and Writing Files

File Modes - Reading and Writing Files
In a file handling program we must specify why and how we want to open it. In other words we must specify whether we want to create a new file, or are we overwriting an existing file, or we want to append data in an existing file. To specify it we must use different modes which are provided by C. These modes are usually in single letter like "r", "b", "w", "a". Sometimes a "+" is also used with these modes to provide some additional functionality.
  • The "r" mode - Opens the file for reading. This fails if the file does not exist or cannot be found. The file to be read must be an existing file.
  • "w" - Opens the file as an empty file for writing. If the file exists, its contents are destroyed.
  •  "a" - Opens the file for writing at the end of the file (appending) without deleting its existing contents. If the file is not existing, this mode can create a new file also.

A "+" sign can also be used with these mode to make them even more useful.

  • "r+" Opens the file for both reading and writing. (The file must exist.)
  • "w+" Opens the file as an empty file for both reading and writing. If the file exists, its contents are destroyed.
  • "a+" Opens the file for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn't exist.
Following is the list of various modes in which we can handle a file.

Mode           Type of file     Read Write         Create            Truncate
  1. r          text                    Read
  2. rb+      binary                Read
  3. r+        text                    Read Write
  4. r+b      binary                Read Write
  5. rb+      binary                Read Write
  6. w         text                   Write                   Create                Truncate
  7. wb       binary               Write                   Create                Truncate
  8. w+       text                   Read Write           Create                Truncate
  9. w+b     binary               Read Write           Create                Truncate
  10. wb+     binary               Read Write           Create                Truncate
  11. a          text                   Write                    Create
  12. ab        binary               Write                    Create
  13. a+         text                  Read Write          Create
  14. a+b         binary            Write                   Create
  15. ab+         binary            Write                   Create

0 comments:

Post a Comment