1 DOS vs. UNIX files Ending lines with “\r\n” vs. “\n” Reading an entire line at a time getline() To skip white space or not cin >> ch; vs. ch = cin.get();

Slides:



Advertisements
Similar presentations
1 Random number generation Using srand(), rand() & time(0) Searching and Sorting Demo Making searching & sorting more generic Overloading the functions.
Advertisements

File Input/Output. External Files Batch –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
Strings & Text File Input CIS Feb-06. Quiz 1.Write a function Prototype for the function swap_values that takes two integers by reference and does.
9-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
File streams Chapter , ,
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Lecture 18:Topic: I/O Formatting and Files Dale/Weems/Headington
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
1 The UNIX date command myclock.cpp example The C/C++ time() and ctime() functions myclock2.cpp example Inline function definitions Inline class member.
Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
Fundamental Programming Command Line Parameters and File I/O.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
Linux Operations and Administration
ITEC 320 C++ Examples.
C++ Streams Lecture-2.
1 Operating Systems Lecture 2 UNIX and Shell Scripts.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.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.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
1 Chapter 4 Program Input and the Software Design Process.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Chapter Expressions and Interactivity 3. The cin Object 3.1.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Strings (part 2) Dr. Xiao Qin Auburn.
Chapter 9 Strings Copyright © 2016 Pearson, Inc. All rights reserved.
Command Line Arguments
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
File I/O.
Standard Input/Output Streams
Standard Input/Output Streams
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Today’s Lecture I/O Streams Tools for File I/O
Chapter 9 File Streams Computing Fundamentals with C++ 3rd Edition
Chapter 3: Input/Output
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
File I/O in C++ I.
CPS120: Introduction to Computer Science
Reading from and Writing to Files
Reading from and Writing to Files Part 2
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

1 DOS vs. UNIX files Ending lines with “\r\n” vs. “\n” Reading an entire line at a time getline() To skip white space or not cin >> ch; vs. ch = cin.get(); Command line args, again Examples & Demos CSE Lecture 9 – Files & More

2 Rest of the week Introduction to functions & prototypes Function parameters (formal and actual) Value and reference parameters Recursion Template functions Curses I/O Text based windowing function library Read: Sections

3 DOS vs. UNIX Files In DOS ASCII Text Files All lines end withTWO characters or “\r\n” In UNIX ASCII Text Files All lines end with ONE character or ‘\n’ Converting between two in UNIX/Linux dos2unix – converts dos files to UNIX format unix2dos – converts unix files to DOS format

4 DOS vs. UNIX Files How will you know? Open a DOS text file in some UNIX editors like “vi” and you will see a ‘^M’ character at the end of each line These are the ‘\r’ or return characters Open a UNIX text file using a DOS/Windows editor like “notepad” and the whole file appears to be on one line This is because of the missing ‘\r’ characters

5 Reading an entire line To read an entire line at once … Declare a string variable string lineIn; Use getline() to read the whole line from cin getline(cin, lineIn); Or read the whole line from an istream getline(inFile, lineIn);

6 Reading until a given char … You can even read all of the line up to a specific character … To read up to the next period getline(cin, lineIn, ‘.’);

7 Getline() cautions There is another version of getline() that is defined in the istream class and which uses char arrays as input buffers Its arguments are A char array, a limit number, a limit char (‘\n’ by default) It is called like this char buffer[100]; cin.getline(buffer, 100); infile.getline(buffer, 100, ‘.’)

8 Command line args, again … The command line is broken up by white space argc is the count of strings on the command line argv is an indexed list (an array) of strings, from the command line, beginning with the name of the program

9 Sample Program - comline // comline.cpp – JHS // Usage: comline.... #include using namespace std; int main (int argc, char *argv[]) { cout << “Program run w/ following command line.\n"; for (int i=0; i<argc; i++) cout << ' ' << argv[i]; cout << endl; cout << "Command line arguments are...\n"; cout << "argc = " << argc << endl; for (int i=0; i<argc; i++) cout << "argv[" << i << "] " << argv[i] << endl; return 0; }

10 Skipping White Space By default, the input stream extractions (>>) are separated by white space, so this gets the next character that is NOT white space cin >> ch; The get() function gets the next character no matter what it is (whitespace or not) ch = cin.get(); Use what is appropriate See cat.cpp vs. cat2.cpp for difference

11 Demo Programs tocaps (using the (char) cast) tocaps_oops (failing to use the (char) cast) disks (C-style I/O) more2 (uses getline) cat vs. cat2 (ch=cin.get(); vs. cin >> ch;) cat vs../cat (path issues, what gets run)

12 ToCaps … Another use of argc & argv // File: tocaps.cpp - JHS(9/14/2003) // Purpose: // Shows file contents on screen (IN ALL CAPS). // File specified by command line argument. // Discussion: // Demo of loops, file streams, & args to main. // Usage: tocaps #include #include <cctype using namespace std; int main (int argc, char *argv[]) { char charIn; ifstream infile;

13 ToCaps … Another use of argc & argv // do we have a correct command line with filename? if (argc != 2) { cout \n"; exit(1); } // use filename to open file for input // note: argv[0] is the command name “tocaps" // argv[1] is the filename from the command line infile.open(argv[1]); if (infile.fail()) { cout << "File failed to open!" << endl; exit(2); }

14 ToCaps … Another use of argc & argv // loop gets characters one at a time until // end of file is found while ((charIn = infile.get()) != EOF) { if (isalpha(charIn)) // echo upper case equivalent of letter cout << (char)toupper(charIn); //cout << toupper(charIn); in “tocaps_oops.cpp” else // echo other character to screen cout << charIn; } infile.close(); return 0; }

15 Disks … Final example using C-style I/O Program computes the volumes of a sequence of disks and outputs a summary report. A file contains lines of data. Each line describes a number and size of disks of a certain type. Line Format: number(int) diameter(float) thickness(float) type(char) Examples: A G Last line is the sentinel line q

16 Sample “diskdata.txt” File A F R V q

17 Sample run of./disks >./disks diskdata.txt results.txt 3 disks of type A : volume = disks of type F : volume = disks of type R : volume = disks of type V : volume = Total volume of all disks = >

18 Disks.c /* ********************************************************* ** disks.c - JHS 06 (C-style I/O & computing disk volume) ********************************************************* */ #include #define PI int main(int argc, char *argv[]) { FILE *infile, *outfile; int num; float radius, diameter, thickness, volume, total; char type; total = 0.0;

19 Disks.c if (argc != 3) { printf("Usage: disks \n"); return 1; } infile = fopen(argv[1],"r"); if (NULL == infile) { printf("Cannot open input file!\n"); return 2; } outfile = fopen(argv[2],"w"); if (NULL == outfile) { printf("Cannot create output file!\n"); return 3; }

20 Disks.c fscanf(infile,"%d %f %f %c", &num, &diameter, &thickness, &type); while (type != 'q') // while sentinel has not been read { radius = 0.5*diameter; volume = num*(PI*radius*radius*thickness); total = total + volume; /* show the user */ printf("%4d disks of type %c : volume = %10.3f\n", num, type, volume); /* output same information to disk */ fprintf(outfile, "%4d disks of type %c : volume = %10.3f\n", num, type, volume); /* read another line */ fscanf(infile,"%d %f %f %c", &num, &diameter, &thickness, &type); }

21 Disks.c printf("Total volume of all disks = %10.3f\n", total); fprintf(outfile,"Total volume of all disks = %10.3f\n", total); fclose(infile); fclose(outfile); return 0; }

22 Program “cat.cpp” // cat.cpp – JHS 2006 // NOTE: This skips all white space & compresses text // Usage: cat #include using namespace std; int main (int argc, char *argv[]) { char charIn; ifstream infile; // do we have a correct command line with filename? if (argc != 2) { cout \n"; exit(1); }

23 Program “cat.cpp” // use filename to open file for input // argv[1] is the filename from the command line infile.open(argv[1]); if (infile.fail()) { cout << "File failed to open!" << endl; exit(2); } // get characters one at a time until end of file found infile >> charIn; // get 1st non whitespace character while (!infile.eof()) { cout << charIn; // echo character to screen infile >> charIn; // get next non whitespace character } infile.close(); return 0; }

24 Program “cat2.cpp” // cat2.cpp – JHS 2006 // NOTE: This reads and displays ALL text, even whitespace // Usage: cat2 #include using namespace std; int main (int argc, char *argv[]) { char charIn; ifstream infile; // do we have a correct command line with filename? if (argc != 2) { cout \n"; exit(1); }

25 Program “cat2.cpp” // use filename to open file for input // argv[1] is the filename from the command line infile.open(argv[1]); if (infile.fail()) { cout << "File failed to open!" << endl; exit(2); } // get characters one at a time until end of file found while ((charIn = infile.get()) != EOF) // get char & test { cout << charIn; // echo character to screen } infile.close(); return 0; }

26 Program – more2.cpp // more2.cpp – JHS 2006 // This program shows a file contents on the screen // (one page at a time), using getline() // Usage: more2 #include using namespace std; int main (int argc, char *argv[]) { string lineIn; ifstream infile; int lines; // number of lines shown before pause bool quit; char resp;

27 Program – more2.cpp // do we have a correct command line with filename? if (argc != 2) { cout \n"; exit(1); } // use filename to open file for input // argv[1] is the filename from the command line infile.open(argv[1]); if (infile.fail()) { cout << "File failed to open!" << endl; exit(2); } // get lines of text until end of file found lines = 0; quit = false; getline(infile,lineIn); // get first line

28 Program – more2.cpp while ((!infile.eof()) && (!quit)) { // NOTE: getline consumes the ‘\n’ at end of each line // but it is not made part of string. cout << lineIn << endl; // echo text line to screen lines++; if (lines > 24) { resp = cin.get(); if (resp == 'q') quit = true; // set flag so program quits else lines = 0; // reset line count } getline(infile,lineIn); // get next line of text } infile.close(); return 0; }

29 Path issues – what gets executed? Your bash shell in Linux is the command interpreter It’s environment can be displayed using set and env One of the variables is path or PATH The order of directories in the path determines which version of a command or program gets run when you type its name Typing a command this way./prog tells the shell to look in the current directory for prog rather than searching the path

30 Path issues – what gets executed? Example There is a Linux command “disks” and we have a program called “disks” Type disks and the Linux command is run > disks disks: you must be root to run this program Type./disks and our program is run >./disks Usage: disks Try cat &./cat to see the difference between the Linux cat and ours.