Fundamentals of Programming. Lecture 10 Hamed Rasifard

Similar documents
UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

C Programming Language

25.2 Opening and Closing a File

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

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

PROGRAMMAZIONE I A.A. 2017/2018

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

File Handling. Reference:

Input/Output and the Operating Systems

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

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

File IO and command line input CSE 2451

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

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

C-Refresher: Session 10 Disk IO

Computer Programming Unit v

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

EM108 Software Development for Engineers

UNIX System Programming

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

M.CS201 Programming language

Data File and File Handling

Data Files. Computer Basics

File I/O. Preprocessor Macros

System Software Experiment 1 Lecture 7

Standard I/O in C, Computer System and programming in C

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

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

2009 S2 COMP File Operations

Computer programming

Lecture 9: File Processing. Quazi Rahman

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

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

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

CE Lecture 11

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

CSC 270 Survey of Programming Languages. Input and Output

System Programming. Standard Input/Output Library (Cont d)

Introduction to file management

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

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

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b =

Input / Output Functions

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

HIGH LEVEL FILE PROCESSING

CP2 Revision. theme: file access and unix programs

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

CS240: Programming in C

C PROGRAMMING. Characters and Strings File Processing Exercise

Computer System and programming in C

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

Intermediate Programming, Spring 2017*

IO = Input & Output 2

CSI 402 Lecture 2 (More on Files) 2 1 / 20

structs as arguments

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

Standard File Pointers

UNIT- 2. Binary File

Standard C Library Functions

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

The fopen command can open an external file in C language. If the file is exist, the file pointer is not NULL. Otherwise, the file pointer is NULL.

Introduction to Computer Programming Lecture 18 Binary Files

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

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

ENG120. Misc. Topics

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

C File Processing: One-Page Summary

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

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

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

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Week 9 Lecture 3. Binary Files. Week 9

CSE 410: Systems Programming

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING

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

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

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

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

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

Naked C Lecture 6. File Operations and System Calls

Ch 11. C File Processing (review)

Engineering program development 7. Edited by Péter Vass

Chapter 14 - Advanced C Topics

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

Programming & Data Structure

Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

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

File and Console I/O. CS449 Spring 2016

C Programming 1. File Access. Goutam Biswas. Lect 29

C Basics And Concepts Input And Output

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Programming Fundamentals

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

mywbut.com 12 File Input/Output

Library Functions. General Questions

Operating System Labs. Yuanbin Wu

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Transcription:

Fundamentals of Programming Lecture 10 Hamed Rasifard 1

Outline File Input/Output 2

Streams and Files The C I/O system supplies a consistent interface to the programmer independent of the actual device being accessed. That is, the C I/O system provides a level of abstraction between the programmer and the device. This abstraction is called a stream, and the actual device is called a file. 3

Streams The C file system is designed to work with a wide variety of devices, including terminals, disk drives, and tape drives. Even though each device is very different, the buffered file system transforms each into a logical device called a stream. Because streams are largely device independent, the same function that can write to a disk file can also write to another type of device, such as the console. There are two types of streams: text and binary. 4

Text Streams A text stream is a sequence of characters. Standard C states that a text stream is organized into lines terminated by a newline character. The newline character is optional on the last line. text stream, certain character translations may occur as required by the host environment. 5

Binary Streams A binary stream is a sequence of bytes that has a one-to-one correspondence to the bytes in the external device that is, no character translations occur. The number of bytes written (or read) is the same as the number on the external device. 6

Files In C, a file may be anything from a disk file to a terminal or printer. A stream could be associated with a specific file by performing an open operation. Once a file is open, information can be exchanged between it and your program. 7

File System Basics The header <stdio.h> provides the prototypes for the I/O functions and defines these three types: size_t, fpos_t, and FILE. The size_t type is some variety of unsigned integer, as is fpos_t. Also defined in <stdio.h> are several macros: NULL, EOF, FOPEN_MAX, SEEK_SET, SEEK_CUR, and SEEK_END. 8

The File Pointer A file pointer is a pointer to a structure of type FILE. It points to information that defines various things about the file, including its name, status, and the current position of the file. In order to read or write files, your program needs to use file pointers. The file pointer declaration: FILE *fp; 9

Opening a File The fopen( ) function opens a stream for use and links a file with that stream. Then it returns the file pointer associated with that file. fopen( ) function prototype: FILE *fopen(const char *filename, const char *mode); 10

Values for Mode Mode r 11 Meaning Open a text file for reading w Create a text file for writing a Append to a text file rb Open a binary file for reading wb Create a binary file for writing ab Append to a binary file r+ Open a text file for read/write w+ Create a text file for read/write a+ Append or create a text file for read/ r+b write Open a binary file for read/write w+b Create a binary file for read/write a+b Append or create a binary file for read/ write

Closing a File The fclose( ) function closes a stream that was opened by a call to fopen( ). It writes any data still remaining in the disk buffer to the file and does a formal operating-systemlevel close on the file. Failure to close a stream invites all kinds of trouble, including lost data, destroyed files, and possible intermittent errors in your program. fclose( ) function prototype: 12 int fclose(file *fp);

Writing a Character The C I/O system defines two equivalent functions that output a character: putc( ) and fputc( ). The putc( ) function writes characters to a file that was previously opened for writing using the fopen( ) function. putc() prototype: int putc(int ch, FILE *fp); 13

Reading a Character There are also two equivalent functions that input a character: getc( ) and fgetc( ). The getc( ) function reads characters from a file opened in read mode by fopen( ). gutc() prototype: int gutc(file *fp); 14

A Simple Disk Program #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fp; char ch; if(argc!=2) { printf(''you forgot to enter the filename.\n"); exit(1); if((fp=fopen(argv[1], "w"))==null) { printf(''cannot open file.\n"); exit (1); do { ch = getchar(); putc(ch, fp); while (ch!= '$'); fclose(fp); return 0; 15

Reading Files and Displays Them #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fp; char ch; if(argc!=2) { printf("you forgot to enter the filename.\n"); exit(1); if((fp=fopen(argv[1], "r"))==null) { printf("cannot open file.\n"); exit(1); ch = getc(fp); /* read one character */ while (ch!=eof) { putchar(ch); /* print on screen */ ch = getc(fp); fclose(fp); return 0; 16

feof( ) Function getc( ) returns EOF when the end of the file has been encountered. Testing the value returned by getc( ) may not be the best way to determine when you have arrived at the end of a file. C includes the function feof( ), which determines when the end of the file has been encountered feof( ) function prototype: int feof(file *fp); 17

Copy a File #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *in, *out; char ch; if(argc!=3) printf(''you forgot to enter a filename.\n"); exit(1); if((in=fopen(argv[1], "rb"))==null) { printf("cannot open source file.\n"); exit(1); if((out=fopen(argv[2], "wb")) == NULL) { printf("cannot open destination file.\n"); exit(1); /* This code actually copies the file. */ while(!feof(in)) { ch = getc(in); if(!feof(in)) putc(ch, out); fclose(in); fclose(out); return 0; 18

rewind( ) Functions The rewind( ) function resets the file position indicator to the beginning of the file specified as its argument. feof( ) function prototype: void rewind(file *fp); 19

Going to Beginning of a File #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[80]; FILE *fp; if((fp = fopen("test", "w+"))==null) { printf("cannot open file.\n"); exit(1); do { printf("enter a string (CR to quit):\n"); gets(str); strcat(str, "\n"); /* add a newline */ fputs(str, fp); while(*str!='\n'); /* now, read and display the file */ rewind(fp); /* reset file position indicator to start of the file. */ while(!feof(fp)) { fgets(str, 79, fp); printf("%s", str); return 0; 20

fflush() Function If you wish to flush the contents of an output stream, use the fflush( ) function. This function writes the contents of any buffered data to the file associated with fp. If you call fflush ( ) with fp being null, all files opened for output are flushed. fflush() function prototype: 21 int fflush(file *fp);

fread( ) and fwrite( ) Functions To read and write data types that are longer than 1 byte, the C file system provides two functions: fread( ) and fwrite( ). These functions allow the reading and writing of blocks of any type of data. One of the most useful applications of fread( ) and fwrite( ) involves reading and writing user- defined data types, especially structures. fread( ) and fwrite( ) functions prototype: size_t fread(void *buffer, size_t num_bytes, size_t count, FILE *fp); size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp); 22

A Simple Mailing list #include <stdio.h> #include <stdlib.h> #define MAX 100 struct addr { char name[30]; char street[40]; char city[20]; char state[3]; unsigned long int zip; addr_list[max]; void init_list (void), enter(void); void delete(void), list(void); void load(void), save(void); int menu_select(void), find_free(void); 23

A Simple Mailing list(cont.) int main(void) { char choice; init_list(); /* initialize the structure array */ for(;;) { choice = menu_select(); switch(choice) { case 1: enter(); break; case 2: delete(); break; case 3: list(); break; case 4: save(); break; case 5: load(); break; case 6: exit(0); return 0; 24

A Simple Mailing list(cont.) /* Initialize the list. */ void init_list(void) { register int t; for(t = 0; t < MAX; ++t) addr_list[t].name[0] = '\0'; /* Get a menu selection. */ int menu_select(void) { char s[80]; int c; printf("1. Enter a name\n"); printf(''2. Delete a name\n"); printf("3. List the file\n"); printf(''4. Save the file\n"); printf("5. Load the file\n"); printf(''6. Quit\n"); do { printf("\nenter your choice: "); gets(s); c = atoi(s); while(c < 0 c > 6); return c; 25

A Simple Mailing list(cont.) /* Input addresses into the list. */ void enter(void) { int slot; char s[80]; slot = find_free(); if(s1ot == -1) { printf("\nlist Full"); return; printf("enter name: "); gets(addr_list[slot].name); printf("enter street: "); gets(addr_list[slot].street); printf("enter city: "); gets(addr_list[slot].city); printf("enter state: "); gets(addr_list[slot].state); printf("enter zip: "); gets(s); addr_list[slot].zip = strtoul(s, '\0', 10); 26

A Simple Mailing list(cont.) /* Find an unused structure. */ int find_free(void) { register int t; for(t=0; addr_list[t].name[0] && t<max; ++t) ; if(t==max) return -1; /* no slots free */ return t; /* Delete an address. */ void delete(void) { register int slot; char s[80]; printf("enter record #: "); gets(s); slot = atoi(s); if(s1ot>=0 && slot < MAX) addr_list[slot].name [0] = '\0'; 27

A Simple Mailing list(cont.) /* Display the list on the screen. */ void list (void) { register int t; for(t=0; t<max; ++t) { if(addr_list[t].name[0]) { printf(''%s\n", addr_list[t].name); printf("%s\n", addr_list[t].street); printf("%s\n", addr_list[t].city); printf("%s\n", addr_list[t].state); printf("%lu\n\n", addr_list[t].zip); printf("\n\n"); 28

A Simple Mailing list(cont.) /* Save the list. */ void save(void) { FILE *fp; register int i; if((fp=fopen("maillist", "wb"))==null) { printf(''cannot open file.\n"); return; for(i=0; i<max; i++) if(*addr_list[i].name) if(fwrite(&addr_list[i], sizeof(struct addr), 1, fp)!=1) printf("file write error.\n"); fclose(fp); 29

A Simple Mailing list(cont.) /* Load the file. */ void load(void) { FILE *fp; register int i; if((fp=fopen("maillist", "rb"))==null) { printf(''cannot open file.\n"); return; init_list(); for(i=0; i<max; i++) if(fread(&addr_list[i], sizeof(struct addr), 1, fp)!=l) { if(feof(fp)) break; printf("file read error.\n"); fclose(fp); 30