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

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

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

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

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

Standard C Library Functions

Input / Output Functions

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

Standard File Pointers

UNIX input and output

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

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

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

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

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.

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

File IO and command line input CSE 2451

Lecture 7: file I/O, more Unix

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)

Lecture 8: Structs & File I/O

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 Thr. Young W. Lim Day14 A Thr 1 / 14

25.2 Opening and Closing a File

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

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

CS 220: Introduction to Parallel Computing. Input/Output II. Lecture 8

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

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

Computer Programming Unit v

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

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

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

PROGRAMMAZIONE I A.A. 2017/2018

Input/Output: Advanced Concepts

C Basics And Concepts Input And Output

Goals of this Lecture

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

Input/Output and the Operating Systems

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

CS240: Programming in C

C Programming Language

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Library Functions. General Questions

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

scanf erroneous input Computer Programming: Skills & Concepts (CP) Characters Last lecture scanf error-checking our input This lecture

M.CS201 Programming language

File I/O. Preprocessor Macros

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

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

IO = Input & Output 2

Process Management! Goals of this Lecture!

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

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

HIGH LEVEL FILE PROCESSING

Lecture 9: File Processing. Quazi Rahman

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

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

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

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

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Data File and File Handling

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

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

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

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

File Handling. 21 July 2009 Programming and Data Structure 1

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

C PROGRAMMING. Characters and Strings File Processing Exercise

Organization of a file

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

8. Characters, Strings and Files

Welcome! COMP s1. Programming Fundamentals

The Design of C: A Rational Reconstruction: Part 2

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Basic and Practice in Programming Lab 10

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

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

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

CSCI 4963/6963 Large-Scale Programming and Testing Homework 1 (document version 1.0) Regular Expressions and Pattern Matching in C

File I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

Programming Fundamentals

CSE 230 Intermediate Programming in C and C++ Input/Output and Operating System

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

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

EE458 - Embedded Systems Lecture 4 Embedded Devel.

Stream Model of I/O. Basic I/O in C

The link() System Call. Preview. The link() System Call. The link() System Call. The unlink() System Call 9/25/2017

Programming & Data Structure

Fundamentals of Programming. Lecture 15: C File Processing

ENG120. Misc. Topics

Contents. Programming Assignment 0 review & NOTICE. File IO & File IO exercise. What will be next project?

CSC 270 Survey of Programming Languages. Input and Output

Binghamton University. CS-220 Spring Includes & Streams

DATA STRUCTURES USING C

C programming basics T3-1 -

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

Transcription:

CP 20 slide 1 Tuesday 21 November 2017 Computer Programming: Skills & Concepts (CP) Files in C Julian Bradfield Tuesday 21 November 2017

Today s lecture Character oriented I/O (revision) Files and streams Opening and closing files CP 20 slide 2 Tuesday 21 November 2017

CP 20 slide 3 Tuesday 21 November 2017 Idiom for character-oriented I/O int c; while ((c = getchar())!= EOF) { /* Code for processing the character c */

CP 20 slide 4 Tuesday 21 November 2017 File length int c; int length = 0; while ((c = getchar())!= EOF) { length++; printf("file length is %d\n", length); Don t forget to initialise length, i.e. the length = 0 part.

CP 20 slide 5 Tuesday 21 November 2017 Copying a file int c; while ((c = getchar())!= EOF) { putchar(c); Note that putchar(c) is equivalent to printf("%c", c)

CP 20 slide 6 Tuesday 21 November 2017 Copying a file, checking for errors int c; while ((c = getchar())!= EOF) { /* The manual says putchar returns the character written, or EOF on error (e.g. disk full) */ if ( putchar(c) == EOF ) { perror("error writing file"); exit(1); perror is a standard library function that prints your message to standard error, together with a message describing the system error that was encountered, for example error writing file: No space left on device

CP 20 slide 7 Tuesday 21 November 2017 Example: Count occurrences of uppercase letters int main(void) { int c, countu; countu = 0; while ((c = getchar())!= EOF) { if (isupper(c)) { countu++; printf("%d uppercase letters\n", countu);

CP 20 slide 8 Tuesday 21 November 2017 The Unix I/O model An executing program has a standard input, a standard output, and a standard error. We ve been using these they re all usually the terminal. getchar(), putchar(), printf() etc. all use standard input/output.

Unix file redirection The Unix shell lets one specify the standard input, output and error for the program: Input from a file:./ftour < data50 Output to a file:./ftour > log Input and output redirection:./ftour < data50 > log Input and output from/to a program (piping): cat data50./ftour grep length CP 20 slide 9 Tuesday 21 November 2017

Streams In C we talk about input and output streams getchar() reads from the standard input stream putchar(ch) writes to the standard output stream You might think of a stream as a file but in practice, streams often end at a keyboard, a window or another program. It is more accurate to think of streams as connectors to files etc., which hide the tricky details. (You don t need to know whether your stream is a file, terminal, network connection etc.) CP 20 slide 10 Tuesday 21 November 2017

Standard Streams All C programs begin with three standard streams stdin is read by getchar() stdout is written to by putchar(c) stderr is a second output stream, used by error message functions (e.g. perror()). These streams are defined in stdio.h. Use stderr for error messages and debugging messages of your own. This avoids mixing them up with normal output. CP 20 slide 11 Tuesday 21 November 2017

Using named streams All the standard I/O functions have a variant that has a named stream as a parameter fprintf(stdout, "Hello") printf("hello") putc(c, stdout) putchar(c) getc(stdin) getchar() Use the manual pages to find the variants! Same idea as sscanf, sprintf for strings. N.B. It s very confusing that the stream comes first for most things, but second for putc. CP 20 slide 12 Tuesday 21 November 2017

CP 20 slide 13 Tuesday 21 November 2017 int main(void) { int c, prev = 0; Using named streams while ((c = getc(stdin))!= EOF) { if (prev == 'i' && c == 'z') { putc('s', stdout); else { putc(c, stdout); prev = c;

CP 20 slide 14 Tuesday 21 November 2017 Using new streams Streams have the type FILE *. E.g. FILE *stdin, *stdout, *stderr; FILE *wordlist; Streams do not always end in a file despite the name!

CP 20 slide 15 Tuesday 21 November 2017 Opening files FILE *wordlist; wordlist = fopen("wordlist.txt", "r"); if (wordlist == NULL) { perror("can't open wordlist.txt"); return EXIT_FAILURE; /* To be completed */ fclose(wordlist);

fopen() FILE *fopen(const char *path, const char *mode) Opens a stream for the file named path E.g. fopen("output.txt", "w"); E.g. fopen("/usr/include/stdio.h", "r"); The mode selects read or write access This prevents accidents Anyway, you can t write to a CD-Rom. fopen() returns NULL on failure CP 20 slide 16 Tuesday 21 November 2017

fopen() modes "r": Open text file for reading "w": Open text file for writing "a": Open text file for appending and several others... What happens if the file exists already? CP 20 slide 17 Tuesday 21 November 2017

CP 20 slide 18 Tuesday 21 November 2017 Copying a File FILE *in, *out; in = fopen("wordlist.txt", "r"); out = fopen("copy.txt", "w"); while ((c = getc (in))!= EOF) { putc(c, out); fclose(in); fclose(out); We don t really (normally) copy files one character at a time, because it s very inefficient. There are other functions (fread and fwrite) for reading/writing many characters at once.

CP 20 slide 19 Tuesday 21 November 2017 fclose() discards a stream fclose() It is good practice to close streams when they are no longer needed, to avoid operating system limits. Exiting a program closes all streams.

perror(): reporting errors fopen() may return NULL for many reasons File not found Invalid path Permission denied Out of disk space Etc. perror() prints an error related to the last failed system call, as we ve already shown. CP 20 slide 20 Tuesday 21 November 2017

CP 20 slide 21 Tuesday 21 November 2017 Buffering (Most) streams are buffered: Text written to a stream may not appear immediately. fflush(file *stream) forces the pending text on a stream to be written. As does fclose(stream). fprintf(stream, "\n"); Streams connected to terminals are usually flushed after each newline character (and whenever you read from the terminal). stderr is not buffered: a character appears as soon as written.

Summary: Streams Have the type FILE * Programs start with three streams stdin stdout stderr CP 20 slide 22 Tuesday 21 November 2017

Summary: New functions fopen() open a stream for a file getc() similar to getchar() putc() similar to putchar() fprintf() similar to printf() fscanf() similar to scanf() fclose() closes a stream fflush() flushes a buffer perror() reports an error in a system call CP 20 slide 23 Tuesday 21 November 2017