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

Similar documents
Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

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

File IO and command line input CSE 2451

2009 S2 COMP File Operations

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

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

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

25.2 Opening and Closing a File

Input/Output and the Operating Systems

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

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

Input / Output Functions

File I/O. Preprocessor Macros

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

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

CS240: Programming in C

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC 1107: Structured Programming

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

Goals of this Lecture

Standard File Pointers

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

CSC 1107: Structured Programming

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

Character Arrays. strlen("hello, world"); /* string constant */ strlen(array); /* char array[100]; */ strlen(ptr); /* char *ptr; */

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

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

Engineering program development 7. Edited by Péter Vass

Computer Programming Unit v

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

UNIX System Programming

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

File Handling. Reference:

EM108 Software Development for Engineers

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

CSC 270 Survey of Programming Languages. Input and Output

HIGH LEVEL FILE PROCESSING

M.CS201 Programming language

Data File and File Handling

CE Lecture 11

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

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

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

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

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

8. Characters, Strings and Files

structs as arguments

Lab # 4. Files & Queues in C

Text Output and Input; Redirection

Process Management! Goals of this Lecture!

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

Course organization. Course introduction ( Week 1)

1 The CTIE processor INTRODUCTION 1

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

Introduction. Files. 3. UNIX provides a simple and consistent interface to operating system services and to devices. Directories

C-Refresher: Session 10 Disk IO

PROGRAMMAZIONE I A.A. 2017/2018

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

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Basic and Practice in Programming Lab 10

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

Simple Output and Input. see chapter 7

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

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

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

IO = Input & Output 2

Lecture 03 Bits, Bytes and Data Types

How do we define pointers? Memory allocation. Syntax. Notes. Pointers to variables. Pointers to structures. Pointers to functions. Notes.

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

Naked C Lecture 6. File Operations and System Calls

CSE 410: Systems Programming

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

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

Summer June 15, 2010

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

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

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

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C

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.

C Basics And Concepts Input And Output

Programming Fundamentals

Lecture 8: Structs & File I/O

Introduction to file management

System Software Experiment 1 Lecture 7

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C

Advanced C Programming Topics

Lecture 9: File Processing. Quazi Rahman

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

CS1003: Intro to CS, Summer 2008

Contents. A Review of C language. Visual C Visual C++ 6.0

CSC209 Review. Yeah! We made it!

Lecture 7: file I/O, more Unix

Princeton University. Computer Science 217: Introduction to Programming Systems. I/O Management

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

Transcription:

File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ <stdio.h> header contains a structure definition with typedef name FILE that contains component variables (buffer, etc.) used in file I/O You don't need to know the details of these structs to use simple file I/O Use standard file access functions such as fopen() 1

File Access To open a file Function prototype fopen : FILE * fopen(const char *name, const char * mode); To ask fopen to open file (character string "name") in a particular "use mode". fp = fopen(name, mode) fp is the return value: set to NULL if fopen fails Legal use mode values: "r" for read, "w" for write, and "a" for append 2

File Access An "r" mode file can be used like stdin Function prototype getc: int getc(file *stream); To get a char from an "r" file c = getc(fp); c is the return value: Return value is the character read from the file OR Set to EOF if getc fails 3

File Access A w or a" mode file can be used like stdout Function prototype putc: int putc(int c, FILE *stream); To put a character to a w or a file status = putc(c, fp) Return value: set to EOF if putc fails 4

File Access When we fopen a file in "w" or "a" mode: If the file does not already exist, it will be created (like the vi editor creates a new file). If the file does already exist, then "w" mode fopen will destroy the old contents (like the command mv) and "a" mode will append new contents to the end of the existing file (like "save" command in mail). 5

File Access When you have finished reading from a file or writing to a file, call fclose to close the file status = fclose(fp); Function prototype: int fclose(file *stream);) Function fclose( ) returns: Zero for success OR EOF if an error occurs 6

File Access Every file open requires resources and there is a limit on number of files open at any one time close each fp when done using it close all files before program termination FILE structure has a buffer for disk data in memory When putc returns data may not get written to file THE DATA IS NOT SAFELY ON DISK YET! Functions fclose( ) and fflush( ) flush buffer to disk 7

File Access When a C program is started, the operating system opens three files and provides file pointers (FILE *) to them: stdin, stdout, and stderr We can now define getchar and putchar as macros: #define getchar( ) getc(stdin) #define putchar(c) putc((c), stdout) /* why (c) in parens? */ Other file oriented analogs for input / output functions: int fscanf(file *fp, char *format,...); /* mode must be "r" int fprintf(file *fp, char *format,...); /* mode "w" or "a" 8

Error Handling Trying to read a file that does not exist is an error, There are other errors as well: reading or writing a file without appropriate permission There are three streams opened by the O/S when a program begins execution, stdin, stdout, and stderr. stderr usually goes to the screen even if stdout is redirected to a file prog... >outfile /* redirect stdout; overwrite */ prog... >&outfile /* redirect stdout and stderr */ prog... >>outfile /* redirect stdout; append */ 9

Error Handling How to write a program so error msgs go to stderr? char *prog = argv[0]; /* pick up command name */ if ((fp = fopen(*++argv, "r")) == NULL) { fprintf(stderr, "%s: can't open %s\n", prog, *argv); exit(1); } Variable prog is a pointer to char array containing the command name used to invoke this program and *argv is a pointer to char array containing the file name that couldn t be opened 10

Error Handling The exit(int) function (arg: 0-255) terminates program execution and returns argument to invoking process (debugger, shell, fork parent) Of course, a "return value" from main program would do this as well, but exit() will terminate execution as if we executed a return from main(), and can be called from anywhere in program! A zero returned by a program means no error You can use conventions for meaning of non-zero values - best to keep the values positive 11

Error Handling To show how the return value may be used: UNIX conditional sequence && % gcc myprog.c && a.out Second program executes only if first returns == 0 UNIX conditional sequence % gcc myprog.c echo compilation failed Second program executes only if first returns!= 0 12

Error Handling Note a problem with program on pg. 163 To handle errors, should use: #include <errno.h> The function ferror() tells us the last error that occurred for a stream if (ferror(stdout)) { fprintf(stderr, %s: error writing stdout\n, prog); exit(2); } 13

Error Handling If not exiting, to avoid retaining a stale error value from a previous failed operation, use: void clearerr(file *stream); Example: clearerr(stdout); 14

Error Handling More generally, errno.h contains a macro "errno" that can be tested; it is zero if there is no problem and non-zero otherwise Text in B1.7 says errno "may" contain an error number; it will contain one if there has been an error any error, not just in a stream unless the error is so serious it corrupted the error structs We can use the function perror to write out the error msg associated with errno, but we have to test for error right after it occurs to get right one 15

Error Handling We can use the function perror to write out standard error message associated with errno, but we have to test for error right after it occurs to get correct one if (errno!= 0) { perror("error at myprog: exiting."); exit(2); } perror will print out a standard error message corresponding to integer in errno, as if by: fprintf(stderr, "%s: %s\n", s, "error message"); 16

Line Input and Output, K&R 7.7 The standard C library equivalents to getline and putline: fgets and fputs Function fgets like getline() from a file char *fgets(char *line, int maxline, FILE *fp); Reads the next input line (including '\n' at the end) from file fp into the char array line at most maxline-1 chars will be read then a terminal '\0' will be added. Returns ptr to line or NULL (means EOF) 17

Line Input and Output /* sample code to understand fgets similar to getline */ char *fgets(char *s, int n, FILE *iop) { register int c; register char *cs; cs = s; while (--n >0 && (c = getc(iop))!= EOF)) if ((*cs++ =c) == '\n') break; *cs = '\0'' return (c == EOF && cs == s)? NULL : s; } 18

Line Input and Output Function fputs writes line to fp int fputs(char *line, FILE *fp); It returns EOF if error occurs (disk fills up?) otherwise it returns zero Can use perror to print out exact error cause (to stderr, not user screen) 19