Skip to content Skip to navigation Skip to collection information

OpenStax-CNX

You are here: Home » Content » Programming Fundamentals - A Modular Structured Approach using C++ » File Input and Output

Navigation

Table of Contents

Lenses

What is a lens?

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

This content is ...

Endorsed by Endorsed (What does "Endorsed by" mean?)

This content has been endorsed by the organizations listed. Click each link for a list of all content endorsed by the organization.
  • CCQ display tagshide tags

    This collection is included in aLens by: Community College of Qatar

    Comments:

    "Used in the Computer Programming Fundamentals I course."

    Click the "CCQ" link to see all content they endorse.

    Click the tag icon tag icon to display tags associated with this content.

Affiliated with (What does "Affiliated with" mean?)

This content is either by members of the organizations listed or about topics related to the organizations listed. Click each link to see a list of all content affiliated with the organization.
  • OrangeGrove display tagshide tags

    This collection is included inLens: Florida Orange Grove Textbooks
    By: Florida Orange Grove

    Click the "OrangeGrove" link to see all content affiliated with them.

    Click the tag icon tag icon to display tags associated with this content.

  • Houston Community College display tagshide tags

    This collection is included in aLens by: Houston Community College

    Comments:

    "COSC1436 Programming Funaamentals I"

    Click the "Houston Community College" link to see all content affiliated with them.

    Click the tag icon tag icon to display tags associated with this content.

  • Featured Content display tagshide tags

    This collection is included inLens: Connexions Featured Content
    By: Connexions

    Comments:

    "Programming Fundamentals - A Modular Structured Approach Using C++ is a new course written by Kenneth Leroy Busbee, a faculty member at Houston Community College. This text introduces students to […]"

    Click the "Featured Content" link to see all content affiliated with them.

    Click the tag icon tag icon to display tags associated with this content.

Also in these lenses

  • Busbee's Compter Science display tagshide tags

    This collection is included inLens: Busbee's Computer Science Lens
    By: Kenneth Leroy Busbee

    Comments:

    "Texas Common Course Numbering: COSC1336 or COSC1436"

    Click the "Busbee's Compter Science" link to see all content selected in this lens.

    Click the tag icon tag icon to display tags associated with this content.

  • Lens for Engineering

    This module and collection are included inLens: Lens for Engineering
    By: Sidney Burrus

    Click the "Lens for Engineering" link to see all content selected in this lens.

  • eScience, eResearch and Computational Problem Solving

    This collection is included inLens: eScience, eResearch and Computational Problem Solving
    By: Jan E. Odegard

    Click the "eScience, eResearch and Computational Problem Solving" link to see all content selected in this lens.

Recently Viewed

This feature requires Javascript to be enabled.

Tags

(What is a tag?)

These tags come from the endorsement, affiliation, and other lenses that include this content.
 

File Input and Output

Module by: Kenneth Leroy Busbee. E-mail the author

Summary: An introduction to file input and output with examples within the C++ programming language.

Overview of File I/O in C++

We need to understand how to open, read, write and close text files. The following File Input/Output terms are explained:

Text File – A file consisting of characters from the ASCII character code set. Text files (also know an ASCII text files) contain character data. When we create a text file we usually think of it consisting of a series of lines. On each line are several characters (including spaces, punctuation, etc.) and we generally end the line with a return (this a character within the ASCII character code set). The return is also known as the new line character. You are most likely already familiar with the escape code of \n which is used within C++ to indicate a return character when used with in a literal string with the cout.

A typical text file consisting of lines can be created by text editors (Notepad) or word processing programs (Microsoft Word). When using a word processor you must usually specify the output file as text (.txt) when saving it. Most source code files are ASCII text files with a unique file extension; such as C++ using .cpp, Pascal using .pas, Cobol using .cob, etc. Thus, most compiler/Integrated Development Environment software packages (such as the Bloodshed Dev-C++ 5 compiler/IDE) can be used to create ASCII text files.

Filename – The name and its extension. Most operating systems have restrictions on which characters can be used in filenames. Example for MS-DOS and Windows: Lab_05.txt

Because some operating systems do not allow spaces, we suggest that you use the underscore where needed for spacing in a filename.

Filespec – The location of a file along with its filename. It is short for file specification. Most operating systems have a set of rules on how to specify the drive and directory (or path through several directory levels) along with the filename. Example for MS-DOS and Windows: C:\myfiles\cosc_1436\Lab_05.txt

Because some operating systems do not allow spaces, we suggest that you use the underscore where needed when creating folders or sub-directories.

Open – Your program requesting the operating system to let it have access to an existing file or to open a new file. Within C++ this is accomplished by including the header file: <fstream> File Input/Output is handled in C++ by using a pre-defined class of data objects, similar to the way string data type is handled. This class of objects has both data type names and functions built to specifically accomplish opening and closing a file.

Within your program you create a local storage variable with the data type of fstream like this:

fstream inData;

This variable will be used to store the device token that the operating system assigns to the file being opened. Thus, opening a file uses a class member function call like this:

inData.open("C:\\myfiles\\cosc_1436\\Lab_05.txt", ios::in);

The two parameters passed to the function are the filespec and the method that you want to use the file (in this example as input). The function provides a returning value of a device token from the operating system and it is stored in the variable named inData.

It is considered good programming practice to determine if the file was opened properly. The device token should be a non zero value. It the operating system gives you the value of zero it was not able to open the file. The reason it usually can't open a file is because the filespec is wrong (misspelled or not typed case consistent in some operating systems) or the file is not stored in the location specified. We often test the device token by using an if then control structure with the action consisting of stopping the program if it is true that you got the zero. The first line of the if then control structure looks like this:

if (!inData)

Don’t be misled by the not operator. This reads "if it is true that the token stored in inData is zero". If inData is zero, noting zero is 1 or true.

Read – Moving data from a device that has been opened into a memory location defined in your program. When reading text files that have integer or floating-point constants, the operating systems converts the text symbols to a binary number. The operator used is the extraction or read operator. An example of reading is:

inData >> next_number

This expression is similar to reading from the standard input device (aka the keyboard):

cin >> next_number

The "cin" is a predefined device token associated with the Standard Input and Output devices. For our file reading example you might say, "Go to the device identified by the token stored in the inData variable and read in the next value storing it in the next_number variable within my program".

Write – Moving data from a memory location defined in your program to a device that has been opened. When writing integer or floating-point data types, the operating system converts the binary number into the proper text symbols. The operator used is the insertion or write operator. An example of writing is:

outData << "Total is: " << total << endl;

This expression is similar to writing to the standard output device (aka the monitor):

cout << "Total is: " << total << endl;

The "cout" is a predefined device token associated with the Standard Input and Output devices. For our file writing example you might say, "Go to the device identified by the token stored in the outData variable and write the items listed (the string constant then the value stored in my program variable named total then the endl or new line or the return character)".

Close – Your program requesting the operating system to release a file that was previously opened. There are two reasons to close a file. First, it releases the file and frees up the associated operation system resources. Second, if closing a file that was opened for output; it will clear the out the operating system’s buffer and insure that all of the data is physically stored in the output file. Some examples of closing files:

inData.close();

outData.close();

You need to study this module in conjunction with the demo file provided.

Demonstration Program in C++

Creating a Folder or Sub-Folder for Source Code Files

Depending on your compiler/IDE, you should decide where to download and store source code files for processing. Prudence dictates that you create these folders as needed prior to downloading source code files. A suggested sub-folder for the Bloodshed Dev-C++ 5 compiler/IDE might be named:

  • Demo_Programs

If you have not done so, please create the folder(s) and/or sub-folder(s) as appropriate.

Download the Demo Program

Download and store the following file(s) to your storage device in the appropriate folder(s). Following the methods of your compiler/IDE, compile and run the program(s). Study the source code file(s) in conjunction with other learning materials. You may need to right click on the link and select "Save Target As" in order to download the file.

Download from Connexions: Demo_File_IO.cpp

Download from Connexions: Demo_File_IO_Input.txt

After you run the program use a text editor to examine the Demo_File_IO_Output.txt file created by the program. You should see the output as: Total is: 33.3

Definitions

Definition 1: text file
A file consisting of characters from the ASCII character code set.
Definition 2: filename
The name and its extension.
Definition 3: filespec
The location of a file along with its filename.
Definition 4: open
Your program requesting the operating system to let it have access to an existing file or to open a new file.
Definition 5: device token
A key value provided by the operating system to associate a device to your program.
Definition 6: read
Moving data from a device that has been opened into a memory location defined in your program.
Definition 7: write
Moving data from a memory location defined in your program to a device that has been opened.
Definition 8: close
Your program requesting the operating system to release a file that was previously opened.

Collection Navigation

Content actions

Download:

Collection as:

PDF | More downloads ...

Module as:

PDF | More downloads ...

Add:

Collection to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks

Module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks