text files

17
TEXT FILES

Upload: guang

Post on 04-Jan-2016

42 views

Category:

Documents


0 download

DESCRIPTION

TEXT FILES. CIN / COUT REVIEW. We are able to read data from the same line or multiple lines during successive calls. Remember that the extraction operator (>>) skips any leading white space (spaces, tabs, newlines) characters before reading the data. User Input 45 67\n 3 8\n. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: TEXT FILES

TEXT FILES

Page 2: TEXT FILES

CIN / COUT REVIEW We are able to read data from the same line or multiple lines during

successive calls. Remember that the extraction operator (>>) skips any leading white

space (spaces, tabs, newlines) characters before reading the data.

User Input

45 67\n

3 8\n

int num1, num2, num3, num4; cin >> num1;cin >> num2;cin >> num3;cin >> num4;

 num1 = 45num2 = 67num3 = 3num4 = 8

Page 3: TEXT FILES

CIN / COUT REVIEW If you want to skip past ALL remaining data (not just white space) on

a line and go to the next line, you can use cin.ignore().

User Input

45 67\n

3 8\n

int num1, num2;

cin >> num1;cin.ignore(100, ‘\n’);cin >> num2;

num1 = 45skips remaining data on line 1num2 = 2

Page 4: TEXT FILES

CIN / COUT REVIEW If you want to read all characters (includig whitespace characters

instead of skipping past them) you can use the cin.get() to read into char type variables.

User Input

4\n

3 8\n

char ch1, ch2, ch3, ch4, ch5;

cin.get(ch1);cin.get(ch2);cin.get(ch3);cin.get(ch4);cin.get(ch5);

ch1 = ‘4’ch2 = ‘\n’ch3 = ‘3’ch4 = ‘ ‘ch5 = ‘8’

Page 5: TEXT FILES

CIN / COUT REVIW To display output to the screen we used “cout”. The cursor remains where the last output occurs unless “endl” or “\

n” is added ( this allows more output to be added to same line).

CODE

cout << “Hello”;cout << “Hello” << endl;

cout << “Good”;cout << “bye”

OUTPUT

Hello_Hello_

Goodbye_

Page 6: TEXT FILES

CIN / COUT REVIEW Output can be formatted using manipulators:

fixed forces floating point number to be displayed in a decimal format (instead of scientific)

setw() sets the display with of output data setprecision() sets number of decimal places to be displayed

int num = 456;float val = 4.8728;

cout << fixed << showpoint << setprecision(2);cout << val;cout << setprecision(1) << val;cout << setw(4) << val;cout << setw(1) << num;cout << setw(5) << num;

OUTPUT

4.874.9_4.9456__456

Page 7: TEXT FILES

CIN / COUT REVIEW “cin” will read data according to the data type of input variable Reading strings stops at the first whitespace character Using “getline()” forces all characters on line to be read

Input data: 435 8.8“\n”

int num; float value; char ch; string words

cin >> value >> ch;

cin >> ch >> num;

cin >> words >> num >> value;

getline(cin, words);

cin >> ch >> ch >> value >> words;

value = 435.0, ch = ‘8’

ch = ‘4’, num = 35

words = “435”, num = 8, value = 0.8

words = “435 8.8”

ch = ‘3”, value = 5.0, words = “8.8”

Page 8: TEXT FILES

TEXT FILES Text File

File Of ASCII Characters Can Be Viewed In Text Editor

Last Character On Line Is “newline” Character (‘/n’) Last Character In The File Is “eof” Character Can Be Created With Any Text Editor (notepad, compiler…)

Input File Stream Stream Of Data

Same As Keyboard Input But From The File Input File Stream Can Be Tricky

Page 9: TEXT FILES

TEXT FILES File Examples

character (or string) Data:

This Is A Test. This Is Only A Test.(‘/n’)

Now Is The Time For All Good Men(‘/n)

To Come To The Aid Of Their Country.(‘/n’)

(eof)

Mixed Data:Smith Joe 111-11-1111 3.85(‘/n)

Able Sam 222-22-2222 3.25(‘/n)

Blow Joe 333-33-3333 2.50(eof)

Page 10: TEXT FILES

USING TEXT FILES Five Steps For File Access

# 1 – Add “#include <fstream>” To Top Of Program Adds Library For File Access

# 2 – Declare File Stream Variable Use Valid Identifier Name Separate File Stream Variables are Required For Text Files

Which are Dependant On the Mode (“read” or “write”)– For Input Stream

• ifstream Identifier - example: ifstream inData;– For Output Stream

• ofstream Identifier - example: ofstream outData;

Page 11: TEXT FILES

USING TEXT FILES Five Steps For File Access (cont.)

#3 – Open The File Stream Use The “open” Function

file-stream-variable.open(physical file name)

example: inData.open(“c:\test.txt);

example: const string FILENAME = “test.txt”;

outData.open(FILENAME.c_str());

Note: You may need to list all backslashes as double backslashes in file names

(e.g. “c:\\study.txt”).

Note: file-stream-variable must be of type ifstream or ofstream

physical filenames can be a literal string or a C string variable

(must append “.c_str()” onto the variable name to convert it to a C string – and be sure to include the “string” header file).

Page 12: TEXT FILES

USING TEXT FILES Five Steps For File Access (cont.)

Potential File “Path” Issues Opening Input File Stream (read only)

Checks For File ExistenceIf Exists File Opened, Read Pointer Placed At Beginning

and File Stream In Non-Error State

If Missing File Stream Is Put Into Error State

Opening Output File Stream (write only) Checks For File Existence

If Exists File Opened, All Data Erased, File Ready For Data

If Missing New File Opened, File Ready For Data

Note – Text Files Can Only Be Open In One Mode At A Time (Read or Write)

Page 13: TEXT FILES

USING TEXT FILES Five Steps For File Access (cont.)

File Stream Status Can Be Used For Error Checking

After opening file “figures.txt” for reading, use the file stream variable to check the results.

inData.open("figures.txt");

if ( !inData )

cout << "Error opening file!" << endl;

else

{

// continue program

}

Result: Error message is issued if program was not able to open file figures.txt.

Page 14: TEXT FILES

USING TEXT FILES Five Steps For File Access (cont.)

#4 – Read Or Write Data File Similar To Standard Input/Output Process Instead Of Using “cin” Use File Stream Variable

– File “study.txt” contains:

35.75 47(‘\n’)

36.50 54(‘\n’) <eof>

– Code: double num1; int num2;

ifstream inData; ofstream outData;

inData >> num1; \\Reads First Number

inData >> num2; \\Reads Second Number

results: num1 = 35.75, num2 = 47

Page 15: TEXT FILES

USING TEXT FILES Five Steps For File Access (cont.)

Instead Of Using “cout” Use File Stream Variable Use Of “manipulators” For Formatting Data Has The Same

Affect On Output File As They Do With Displayed Output (..setprecision(), setw()…etc)

double num1, num2;

– Code: num1 = 53.75875;

num2 = num1 * 2; (106.3175)

outData << fixed << showpoint << setprecision(2);

outData << setw(6) << num1 << ‘ ‘ << set(6) << num2 << endl;

– Result: _53.76 _106.32(\n’)

<eof>

Page 16: TEXT FILES

USING TEXT FILES Five Steps For File Access (cont.)

#5 – Close The Open File When Finished As Soon As File Access Is Completed, Files Should Be

Closed

inData.close();

outData.close();

Leaving Files Open When Not Needed Increases Opportunity Of Corrupted Files

Page 17: TEXT FILES

Using Text Files Five Steps

Include “fstream” Header File At Top Of Program Declare File Stream Variables (ifstream or ofstream) Open The Data File Use File Stream Variable To Access File (not cin/cout) Close Any Open Files When Finished With File

Passing The File Stream To A User Defined Function Must Always Be Passed By Reference syntax For example:

void readFile(ifstream& inData) (function header)

void readFile(ifstream& inData); (prototype)