310201 Fundamental Programming Command Line Parameters and File I/O.

42
310201 Fundamental Programming Command Line Parameters and File I/O.

Transcript of 310201 Fundamental Programming Command Line Parameters and File I/O.

Page 1: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

310201Fundamental Programming

Command Line Parameters and File I/O.

Page 2: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Topics for this Week

• Command Line Parameters,• Passing Functions and File Objects to

other functions,• Sequential File I/O,• Random File I/O.

Page 3: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Command Line Arguments• In command line environments such as

UNIX or DOS you can send parameters to the main program function when it is run.

• This can be a very handy feature.  • Command line parameters provide a means

to pass input to a program without having to be prompted for it.

• For example, we could run a program called my_prog at the DOS command prompt and provide 2 command line parameters (separated by spaces) as follows :my_prog in.dat out.dat

Page 4: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Command Line Arguments - What use are they ?

• Command line arguments are very useful because you can pass input / values directly to your program.

• This means that your program doesn’t need to prompt you for the values it needs when you run it - it can just get on and do the job.

• Once the parameters or command line are setup, the command line can be stored in a shell script (UNIX) or batch file (DOS) and later used to run the program at any time in the future.

• This is often a very handy thing to do – especially when you need to run a program without any user intervention.

Page 5: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

DOS Examples

• Many DOS commands and programs use command line arguments, for example : DOS

CommandEffect / Description

dir /s List all files in the current directory sorted in ascending order by their file name.

copy *.* a:\ Copy all files in current directory to the root directory on the A: drive.

del *.bak Delete all files in current dir with a ".bak" file extension.

Page 6: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Windows Examples :Program Effect / Description

win /sStarts Windows 95 or 98 in "Safe Mode"

notepad mike.txt

Runs the Windows notepad and automatically loads the file "Mike.txt"

Screen Savers

All Windows screen savers go into Preview, Setup, or Run mode according to a command line parameter passed to them.

Help filesWindows Help files can be made context sensitive (i.e. jump straight to the required help item) via a command line parameter.

Virus Checkers

Most popular virus checkers almost always have command line parameters, so that you can specify which files and directories to scan when Windows starts up.

Page 7: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Command Line Arguments - General Syntax

• To accept command line parameters, we need to change the main so that it accepts special parameters.

• For a program to accept command line parameters, the following syntax is required in the main function :void main (int argc, char* argv[ ]){

// … body of main function …}

• where :– argc is the number of command line arguments.– argv[ ] is an array of character strings which are the

actual arguments passed to the program.– argv[0] has a special value. It is the name of the program

that is being executed. e.g. my_prog.

Page 8: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Sample Program#include <iostream.h> // For cin, cout, etc. int main (int argc, char* argv[]){

cout << "\nThere are " << argc << " strings on the command line:\n";

for (int i = 0; i < argc; i++){

cout << "- argv[" << i << "] contains: " << argv[i] << endl;

}return 0;

}

Page 9: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Sample Program – Run #1• Now, if we compile this project, we can then

run the program from the DOS prompt (assuming we are in the same drive and directory as our program) with the command line : 

my_prog 

• Because we have run the program, and supplied no command line parameters, then the output of the program would be :

There are 1 strings on the command line:- argv[0] contains: c:\cpp\my_prog.exe

Page 10: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Sample Program – Run #2• However, if we run the program from the

DOS prompt and pass 3 parameters to the program with the command line : 

my_prog one two three 

• Then the program's output would now be :There are 4 strings on the command line:- argv[0] contains: c:\cpp\my_prog.exe- argv[1] contains: one- argv[1] contains: two- argv[1] contains: three

Page 11: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Command Line Arguments and Numeric Data / Values

• All command line values are passed to your main program as strings, and you need to specially convert any numeric ones to float or int.

• Built in functions in stdlib.h are useful for this (see week 3), such as :– atoi string to int conversion– atof string to float conversion– atol string to long conversion– strtod string to double conversion– etc

Page 12: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Passing Functions as Arguments to Other Functions

• Functions can be passed to other functions !

• When a function is passed as a parameter in a function call only the function name is given.

Page 13: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

double sum_square (double SomeFunction(double a), int m, int n)

{ double sum = 0.0; for (int k = m; k < n; k++) sum += SomeFunction (k) * SomeFunction (k); return sum;

}

double function1 (double n) {

return 1.0 / n;}

double function2 (double n){

return 1.0 / (n * n);}

Page 14: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Passing Functions as Arguments to Other Functions (cont …)

void main(){

// Tell sum_square to invoke function1cout << sum_square (function1, 1, 100) << endl;

 // Tell sum_square to invoke function2cout << sum_square (function2, 1, 100) << endl;

}

• N.B. When a function is passed as a parameter in a function call only the function name is given – none of the function parameters are supplied.

Page 15: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

C++ File Operations• A file is a sequential / serial data structure usually

consisting of data components of the same type.• Files permanently store data. e.g. on magnetic

disk.• Files could be thought of as a permanent one-

dimensional array, with no set / specific dimension.• Usually file access is sequential, but C++ also

provides direct / random access mechanism, which can be used to jump to particular locations in files.

• Files can be plain ASCII text (such as files created with Windows Notepad) or binary. e.g. executable machine code.

Page 16: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Streams or Data Channels • Just as there are input / output data streams

for keyboard entry and screen output, there is also a C++ file stream for input / output to devices such as disks, printers, etc.

• Input / Output (I/O) for keyboard and screen is provide by the iostream class and its derived classes ostream and istream.

• File / peripheral device I/O is provided the fstream (Input and Output), ifstream (Input / Read), and ofstream (Output / Write) classes.

Page 17: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Some File Member Functions Function Description.

eof() Checks for end of file. If you are not at end-of-file, then this function returns zero.

fail() Checks for file operation fail. e.g. Open failure. If some error or failure occurs, then this function returns a non-zero value.

close()Close file

getline()Gets a line of text with spaces.

get()Get a single character.

cin / coutYour normal cin / cout member and formatting functions can also be used, but the same limitations apply to files as with keyboard input.

open()Opens a file.

Page 18: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Steps for Handling Files

1. Define a C++ file object(s) that may be used for input, output or both.

2. Open the disk file(s) in the mode required (Read, Write, or both).

3. Read / Write data To / From File as required.

4. Close file(s) objects.

Page 19: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Steps for Handling Files (cont…)

• Just with any form of input, programs that process files also need to check for errors.

• With file processing, the main areas that need to be checked for errors are when :– opening the file. e.g. files doesn’t exist,

disk error, file locked by another user, etc.– reading from or writing to a file. e.g. out

of disk space, file corrupted / truncated, disk errors, invalid data, etc.

Page 20: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Defining a C++ File Object • Before we can begin working with files we need

to include the fstream header in our project, as follows :

#include <fstream.h> // for file handling

• Now, within our program, we can open files for input, output, or both, as follows :

ifstream Input; // File object to be read (input).ofstream Output; // File object to be written (output).fstream InputOutput; // Both read & write file object

Page 21: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Defining a C++ File Object (cont …)

• In these examples, the file object names used are used to indicate our purpose for the file.

• As with all C++ variable and function names, meaningful names should be used wherever possible.

• For example, if we were reading an input file of student results, then we might declare the following file object :

ifstream Stud_Results_Input_File;

Page 22: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

File Opening Modes • The general syntax for opening a file is :

<file stream object>.open (<disk file name>, <file open mode>, <file protection mode>);

• The file open mode and file protection mode may be optional parameters.

• Example : ifstream Input; // File object to be read

(input).Input.open ("a:\sample.dat"); // Default is read

• Here we have declared the file object to be of type ifstream, which can only be used for input, so there is no need to specify any file open mode.

Page 23: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

File Opening Modes (cont …)

• Another example :ofstream Output; // File to be written

(output).Output.open ("C:\ass1\ass1.txt"); //

Default is write

• Here, we have declared the file object to be of type ofstream, which can only be used for output, so once again there is no need to specify any file open mode.

Page 24: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

File Opening Modes (cont …)

• However, if we declare the file object to be of type fstream, then we must tell C++ how whether we want to read (input) the file, write (output) the file, or both, or append more data onto the end of the file.fstream InputOutput; // Declare file object

• Now, we can open the file for reading (input) :InputOutput ("myfile.dat", ios::in);

• or, open the file for writing (output) :InputOutput ("myfile.dat", ios:: out);

• or, open the file to append data (write) :InputOutput ("myfile.dat", ios::app); // Append data (write)

• or, open the file for both read and write :InputOutput ("myfile.dat", ios::in | ios:: out);

Page 25: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Checking for Open Failure • There are two main methods :

Input.open ("a:\sample.dat");if (Input == 0) // Check Input = 0 or Null on fail{

cerr << "File Open Fail!";exit(1);

}

• orInput.open ("a:\sample.dat");if (Input.fail() != 0) // Check fail member function{

cerr << "File Open Fail!";exit(1);

}

• Use whichever of method you like best.

Page 26: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           • Instead of : if (Input == 0) // Check Input = 0 or Null on

fail 

• you can also use the slightly more obscure method that many C++ programmers use : if (!Input) // Check Input = 0 or Null on fail 

Page 27: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Reading and Writing a File const int MAX = 81;void main(){

char Line [MAX];ifstream Input; // Input file objectofstream Output;

 // **** Write data to the file ****

  Output.open ("c:\sample.txt"); // Open for default read as ASCII file

  if (Output == 0) // Check if open failed{

cerr << "File Open Failed !";exit(1);

}

Page 28: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Reading and Writing a File (cont …)

strcpy (Line, "Line 1 : This will be the first line in the file");Output << Line << endl;strcpy (Line, "Line 2 : This will be the second line in the file");Output << Line << endl;strcpy (Line, "Line 3 : And we could keep adding lines");Output << Line << endl;strcpy (Line, "Line 4 : for as long as we want.");Output << Line << endl;

 Output.close(); // Close the input file

// **** Read in and Display the file **** 

Input.open ("c:\sample.txt"); // Open for default read as ASCII file

Page 29: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Reading and Writing a File (cont …)

if (Input.fail() != 0) // Check if open failed{

cerr << "File Open Failed !";exit(1);

while (Input.eof() == 0) // Repeat until end of file{

Input.getline (Line, MAX); // Read a line from the file

cout << Line << endl; // Display the line to the screen.}

 Input.close(); // Close the input file

Page 30: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Assignment 2 – Start Work Now !• At this point, we have now covered

enough material for you to complete Assignment 2.

• Nothing else we do this term is relevant to Assignment 2.

• Follow the Development Hints and Tips.• Think about things carefully as you go.• If you are finding it difficult, stop work,

and do some reading and tutorial questions.

Page 31: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Random File Access Functions :

• So far, we have looked at sequential processing of files.

• However, as indicated earlier, C++ also provides direct / random access mechanism, which can be used to jump to particular locations in files.

Page 32: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Some Random File Access Functions :

Function Class(include file)

Purpose

tellg () istream Returns current position in input file

tellp () ostream Returns current position in output file

seekg () istream Sets position in input file

seekp () ostream Sets position in output file

Page 33: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Example Random File Access :• To demonstrate some of these functions,

we will now look at an example which :– prompts you to enter the name of a file to

process– prompts you to enter a line of text in this file

to change– searches for and replaces this line of text

with a string of *'s– prompts you for the replacement line of text– adds the new line of text to the end of the file

Page 34: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Example Random File Access (cont …)

• For example, if the input file contained the following :– abcdefg– QWERTY– Mike– Hi There

• and we wanted to change the line "Mike" to "Zebra", then we would end up with a file that looked like :– abcdefg– QWERTY– ****– Hi There– Zebra

Page 35: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Example Random File Access (cont …)

const int SIZE = 81; // MAX LINE SIZE

 

void main()

{

char OldLine [SIZE] = {'\0'}; // Current Line from File.

char NewLine [SIZE] = {'\0'}; // The New Line to add to the file.

char Entry [SIZE] = {'\0'}; // What line the User wants to change.

char FileName [SIZE]= {'\0'}; // File to Open for I/O.

 

long WindowPos = -2; // Current Window Position

int Match_Found = 0; // Flag to indicate if desired line was found.

 

cout << "Enter name of file to open : ";

cin >> FileName; // Ask user for the File to Process.

 

fstream IO_File; // Declare an I/O file object.

Page 36: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Example Random File Access (cont …)

IO_File.open (FileName, ios :: in | ios :: out); // Open for Input and Output

 if (IO_File.fail() != 0) // Check for failure ...{

cerr << "\nThis file could NOT be opened or created.";exit(1);

// Ask the user to enter which line in the file they wish to change.cout << "\nWhich line do you wish to change ? : " << endl;cin >> Entry;

 IO_File >> OldLine; // Read a line from the file.

Page 37: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Example Random File Access (cont …)

// Read all lines in the file and look for a match.while ((IO_File.eof() == 0) && (Match_Found == 0)){

cout << OldLine << endl; 

// See if the current line matches the one the user wants to change.

if (strcmp (OldLine, Entry) == 0){

Match_Found = 1; // We found a match !

  // Move to start of the matching line in the file.IO_File.seekg(WindowPos + 2, ios :: beg);

for (int i = 1; i <= strlen(OldLine); ++i)IO_File << '*'; // Replace Old Line in file with

*'s.// And add a CR/LF.IO_File << endl; 

Page 38: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Example Random File Access (cont …)

// Get the replacement line from the User.cout << "Line found ! What do you wish to change it to ? "

<< endl;cin >> NewLine;

 // Move to the end of the file.IO_File.seekg(0,ios :: end);

 // Add this new line to the end of the fileIO_File << NewLine << endl;

}else{

// We haven't found a match yet - so read another line. 

// Save the Current Windows Position.WindowPos = IO_File.tellg();

 IO_File >> OldLine; // Read a line from the file.

}} // END WHILE

Page 39: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Example Random File Access (cont …)

if (Match_Found == 0)cout << "\nLine not found." << endl;

elsecout << "\nLine now changed to *'s, and new line appended

to bottom of file !"<< endl; 

// Close the I/O File.IO_File.close();

Page 40: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Passing File References to Functions

• We will now look at an example which passes a file object to a function for further processing.

• N.B. This is a pretty silly example - normally a function would be in charge of opening, processing and closing the file. But, this example serves to illustrate the method of passing File References to functions.

Page 41: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Passing File References to Functions (cont …)

const int SIZE = 81; // MAX File Name size void Display_Open_File_To_Screen (ifstream &File_In); void main(){

char FileName [SIZE]= {'\0'}; // File to Open for I/O.  ifstream Input; // Read file object 

cout << "Enter name of file to display : ";cin >> FileName;

 Input.open (FileName); // Open for default read as ASCII fileif (Input.fail() != 0) // Check fail member function{

cerr << "File Open Fail !"; exit(1);

}Display_Open_File_To_Screen (Input);

}

Page 42: 310201 Fundamental Programming Command Line Parameters and File I/O.

                                           

Passing File References to Functions (cont …)

void Display_Open_File_To_Screen (ifstream &File_In)// Function to read a file that has already been opened for INPUT// and display it line by line to the screen, and then close it.{

char Line[81];while (!File_In.eof()) // Check for end of file{

File_In.getline (Line,81,'\n'); // Read file line cout << Line << endl; // Display

}File_In.close(); // Close file

}