Intermediate Programming / C and C++ CSCI 6610

Similar documents
Standard File Pointers

File I/O. Arash Rafiey. November 7, 2017

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

File IO and command line input CSE 2451

Input / Output Functions

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Standard C Library Functions

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

ENCM 335 Fall 2018 Lab 6 for the Week of October 22 Complete Instructions

Introduction. Lecture 5 Files and Streams FILE * FILE *

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Lecture 5 Files and Streams

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

IO = Input & Output 2

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

System Software Experiment 1 Lecture 7

More File Operations. Lecture 17 COP 3014 Spring april 18, 2018

Input/Output: Advanced Concepts

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

C++ Input/Output: Streams

8. Characters, Strings and Files

ENGI 1020 Introduction to Computer Programming R E Z A S H A H I D I J U L Y 2 6,

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Chapter 12. Files (reference: Deitel s chap 11) chap8

Lecture 9: File Processing. Quazi Rahman

C programming basics T3-1 -

C mini reference. 5 Binary numbers 12

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

C Basics And Concepts Input And Output

DATA STRUCTURES USING C

CSCI 6610: Review. Chapter 7: Numbers Chapter 8: Characters Chapter 11 Pointers

UNIT IV-2. The I/O library functions can be classified into two broad categories:

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

ECE551 Midterm Version 1

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

File Access. FILE * fopen(const char *name, const char * mode);

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

Advanced C Programming Topics

Fundamentals of Programming. Lecture 15: C File Processing

Introduction to file management

CS 261 Fall Mike Lam, Professor. Structs and I/O

CS2141 Software Development using C/C++ Stream I/O

Organization of a file

Object Oriented Programming In C++

Chapter 10: File Input / Output

Chapter 8 File Processing

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Topic 2. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

Course organization. Course introduction ( Week 1)

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

CE Lecture 11

Programming Fundamentals

EM108 Software Development for Engineers

UEE1303(1070) S 12 Object-Oriented Programming in C++

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52

Streams - Object input and output in C++

ECE551 Midterm Version 2

Streams. Rupesh Nasre.

211: Computer Architecture Summer 2016

CSCI 171 Chapter Outlines

File (1A) Young Won Lim 11/25/16

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

Computer System and programming in C

The basic nature of string-handling in C causes some problems with input of strings.

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

fopen() fclose() fgetc() fputc() fread() fwrite()

The Design of C: A Rational Reconstruction (cont.)

Programmer s Points to Remember:

C++ files and streams. Lec 28-31

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

Computer Programming: Skills & Concepts (CP) Files in C

Ch 11. C File Processing (review)

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

CSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

Streams in C++ Stream concept. Reference information. Stream type declarations

M.CS201 Programming language

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING CMPE-13/L: COMPUTER SYSTEMS AND C PROGRAMMING SPRING 2012

Lecture 3 The character, string data Types Files

ENG120. Misc. Topics

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Advanced C Programming and Introduction to Data Structures

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

Chapter 10. File Processing 248 FILE PROCESSING

Lab # 4. Files & Queues in C

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

by Pearson Education, Inc. All Rights Reserved. 2

Naked C Lecture 6. File Operations and System Calls

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

CSI 402 Lecture 2 Working with Files (Text and Binary)

Euclid s algorithm, 133

Transcription:

Intermediate Programming / C... 1/16 Intermediate Programming / C and C++ CSCI 6610 Streams and Files February 22, 2016

Intermediate Programming / C... 2/16 Lecture 4: Using Streams and Files in C and in C++ Streams Opening Files File I/O

Intermediate Programming / C... 3/16 Files We will use input text files and output text files. A file is data that is stored on your hard disk or some other device. Files have many properties that the programmer would rather not deal with: Its physical location. Its actual size Decoding the access permissions. How much has been processed so far, and how much remains? Streams were invented to take care of all those troublesome properties of a file.

Intermediate Programming / C... 4/16 Streams A stream is an abstraction that makes files easy to use. An input stream is a data structure that permits you to bring data from a file into your program. An output stream is a data structure that permits you to write your data out to permanent storage. It is implemented as a structure that contains buffers, error flags, pointers, and other parts. In standard C, a stream has type FILE* The tools library uses typedef to define the type name stream as a synonym for FILE* typedef FILE* cstream; In C++, there are istreams and ostreams.

Intermediate Programming / C... 5/16 Opening a File in C: Chapter 14.2 To read from or write to a file, you must first open the file and check to be sure the file was properly opened. Here are two correct approaches. The second one is better. FILE* datafile = fopen("mydata.txt", "r"); // input. if (! datafile) { puts ("Cannot open myfile.txt for input."); exit(1); } #define OUTF "myout.txt" stream outfile = fopen( OUTF, "w"); // output. if (! outfile) fatal ("Cannot open %s for output.", OUTF);

Intermediate Programming / C... 6/16 Opening a File in C++ # include "tools.hpp" # define INF "mydata.txt" # define OUTF "myout.txt" ifstream datafile ("mydata.txt"); // input. if (!datafile) fatal("can t open %s for input", INF); ofstream outfile( OUTF ); if (!outfile.is open()) fatal ("Cannot open %s for output.", OUTF);

Intermediate Programming / C... 7/16 File and eof I/O in C: Chapter 14.4.3 The file-input and file-output functions are like scanf and printf. Here, we read a series of pairs of numbers from one file and write them in reverse order on the other. double x, y; int status; // To store the result of fscanf. for(;;) { status = fscanf( datafile, "%lg %lg", &x, &y ); if( feof( datafile ) ) break; if( status == 0 ) fatal( "File format error" ); // Otherwise, process the data you just read. fprintf( outfile, "%g %g", y, x ); } The program will terminate with a File format error comment if alphabetic data is read when numeric data was expected.

Intermediate Programming / C... 8/16 File I/O and eof in C++ Everything stays the same or becomes easier. double x, y; for(;;) { datafile >>x >>y; if (datafile.eof( )) break; if (!datafile.good()) fatal("file format error"); // Otherwise, process the data you just read. outfile <<y, <<x; } The program will terminate with a File format error comment if alphabetic data is read when numeric data was expected.

Intermediate Programming / C... 9/16 Reading Numbers in C++ Simply use the >> operator. C++ numeric input and output is generic: you write it the same way no matter what the type of the number happens to be. double x; int k float f; for(;;) { datafile >> x >> k >> f; if (datafile.eof( )) break; if (!datafile.good()) fatal("file format error"); // Otherwise, process the data you just read. }

Intermediate Programming / C... 10/16 Reading a Character in C To read the next character, even if it is invisible: char ch; fscanf( datafile, "%c" ); ch = fgetc( datafile ); ch = getc( datafile ); To skip whitespace, then read the next visible character, Put a space before the %: fscanf( datafile, " %c" );

Intermediate Programming / C... 11/16 Reading a Character in C++ To skip whitespace, then read the next visible character: char ch; datafile >> ch; To read the next character, even if it is invisible, set a flag in the stream, thus: datafile >> noskipws >> ch The noskipws flag remains set until the program resets it: datafile >> skipws;

Intermediate Programming / C... 12/16 Reading a String in C Reading a string is more complex than reading a number because a string can be any length. One of the main security vulnerabilities in old C code is that string reads were allowed to store data past the end of the array that was supposed to hold the letters. This is called the buffer overflow problem. It is irresponsible and unprofessional to read a string without limiting the number of chars that can be read. For this reason, you must never use gets(). It provides no way to read a string safely.

Intermediate Programming / C... 13/16 Using fgets() in C char ary [16]; fgets( ary, 16, datafile ); fprintf( outfile, "%s", ary ); fgets() lets you limit the length of an input string to the length of the array that stores it. fgets( char * ary, int n, FILE* strm ); Read characters from strm into the ary until n-1 chars have been read. Store a null terminator after the last input character. fgets() also stops reading if a newline character is found, or end-of-file occurs before reading n-1 chars.

Intermediate Programming / C... 14/16 Using fscanf() to read a string in C fscanf( FILE* strm, char* format, char* ary ); fscanf() lets you limit the length of an input string to the length of the array that stores it. char ary [16]; fscanf( datafile, "%15[^\n]", char* ary ); fprintf( outfile, "%s", ary ); The format must specify a maximum string length that is 1 shorter than ary.

Intermediate Programming / C... 15/16 Reading a String in C++ Reading a string is much simpler in C++ than in C because of the C++ type string. A string has a default length (number of characters), but if you try to store more than that into it, it will grow itself by reallocating the character array to double the current length. So although it is possible to read a char* in C++, it is normally not the right thing to do. A C++ string is the ideal type variable to contain input. You can read the input safely, and later decide how it should be handled. There are two basic ways to read a string.

Intermediate Programming / C... 16/16 >> and getline() datafile >> name; The input operator skips leading whitespace and reads one word into name. It stops when the next whitespace character is found in the datafile. getline (istream& is, string& str); This function reads chars from the stream into the string until the newline is found, or eof happens. The newline is removed from the stream and discarded. It is not stored as part of the string. getline (istream& is, string& str, char delim); This function reads chars from the stream into the string until the specified delimiter is found, or eof happens. The delimiter is removed from the stream and discarded. It is not stored as part of the string.