Input/Output: Advanced Concepts

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

Input / Output Functions

Input/Output and the Operating Systems

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

Advanced C Programming Topics

Standard File Pointers

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

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

Standard C Library Functions

File IO and command line input CSE 2451

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

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

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

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

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

CE Lecture 11

DATA STRUCTURES USING C

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

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

Programming & Data Structure

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

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

211: Computer Architecture Summer 2016

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

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

Course organization. Course introduction ( Week 1)

Unit 4. Input/Output Functions

C Programming Language

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

Fundamentals of Programming. Lecture 11: C Characters and Strings

File I/O. Last updated 10/30/18

C mini reference. 5 Binary numbers 12

System Software Experiment 1 Lecture 7

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

Computer Programming Unit v

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

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

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

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

Formatting functions in C Language

Organization of a file

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

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.

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

UNIX input and output

(T) x. Casts. A cast converts the value held in variable x to type T

CSC 270 Survey of Programming Languages. Input and Output

25.2 Opening and Closing a File

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

Chapter 10: File Input / Output

CSC 1107: Structured Programming

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

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

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

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

Intermediate Programming, Spring 2017*

ENG120. Misc. Topics

EM108 Software Development for Engineers

Pointers and File Handling

Fundamentals of Programming

SWEN-250 Personal SE. Introduction to C

Fundamental of Programming (C)

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

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)

C PROGRAMMING. Characters and Strings File Processing Exercise

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

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

C programming basics T3-1 -

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

8. Characters, Strings and Files

C Programming. Unit 9. Manipulating Strings File Processing.

Programming Fundamentals

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

CSC 1107: Structured Programming

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

CS240: Programming in C

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

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

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

Computer System and programming in C

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

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

File Handling. 21 July 2009 Programming and Data Structure 1

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING UNIT-1

Euclid s algorithm, 133

HIGH LEVEL FILE PROCESSING

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

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

C File Processing: One-Page Summary

Ch 11. C File Processing (review)

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

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

Engineering program development 7. Edited by Péter Vass

Fundamentals of Programming. Lecture 15: C File Processing

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

IO = Input & Output 2

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Chapter 14 - Advanced C Topics

PROGRAMMAZIONE I A.A. 2017/2018

Transcription:

Input/Output: Advanced Concepts CSE 130: Introduction to Programming in C Stony Brook University Related reading: Kelley/Pohl 1.9, 11.1 11.7

Output Formatting Review Recall that printf() employs a control string that may contain conversion specifications (AKA formats) Formats are replaced by specific values when the output is ultimately generated at run-time Formats begin with the prefix character % Formats end with a conversion character that indicates the type of value being substituted into the output

Formatting Your Formats Between the % and the conversion character, a format may contain (in order): Zero or more flags An optional minimum field width (a positive integer) Precede the field width with 0 to zero-pad the output An optional precision (a. followed by a nonnegative integer) An optional h (short) or l (long) modifier for integral types An optional L (long) modifier for float/double types

Flag Options Minus sign ( - ): the argument should be left-aligned in its field Plus sign ( + ): non-negative signed values should begin with a + Space ( ): non-negative signed values should begin with a space Hash ( # ): prints the result in an alternate form based on the conversion character %#o prepends a 0 to octal values %#x prepends 0X to hexadecimal values Zero ( 0 ): pads the field with leading zeros

int i = 123; double x = 0.123456789; Format Argument Actual Output Comment %d i 123" (default) width 3 %05d i 00123" zero-padded %7o i 173 right adjusted octal %-9x i 7b left adjusted hex %-#9x i 0x7b left adjusted alt. hex %10.5f x 0.12346 width 10, precision 5 %-12.5e x 1.23457e-01 left adjusted e-format

Special Strings and scanf() A scanf() conversion specification of the form %[...] means that a special string is to be read in If the first character inside the brackets is ^, the string may not contain any of the other bracketed characters If the first bracketed character is NOT ^, the string may only contain the other bracketed characters e.g., scanf( %[AB \n\t], s); will read in a string that only contains As, Bs, spaces, newlines, and tabs.

Working with Files Files provide stable storage for a program They can be used to hold data between invocations, so that it does not need to be re-entered the next time the program runs File processing (reading and writing data) is similar to console I/O in C Use fprintf() and fscanf(), two variants of the I/O functions we already know

File Pointers Start by creating a pointer to a FILE structure (defined in stdio.h): FILE *infile; The fopen() function opens the specified file and returns a pointer to FILE: infile = fopen( my_file.txt, r );

The fopen() Command fopen() takes two string arguments: the name of the file (including its path) and the opening mode There are three opening modes: r opens a file to read from it w opens a file to (destructively) write to it If the file does not exist, w mode creates it a opens a file to append to its contents Use r+ or w+ to read and write to the same file If fopen() fails to open the file, it returns NULL

Reading From Files getc() reads one character at a time (like getchar()) getc() takes a file pointer as its argument getc() returns EOF (end-of-file) when there are no more characters to read fscanf() works like scanf() for more elaborate input It takes the file pointer as its first argument e.g., fscanf(infile, %c %5d, &letter, &code);

Writing To Files putc() writes one character to a file stream (like put()) putc() takes a char and a file pointer as its arguments putc() returns EOF (end-of-file) on failure fprintf() works like printf() for more elaborate output It takes the file pointer as its first argument e.g., fprintf(outfile, %d %s\n, n, message);

When You re Done... When a C program completes, all open files are closed automatically C limits the number of files that a program can have open at one time (usually to 20 or 64 files) If you re working with a lot of files, you may need to close some of them manually Do this with the fclose() function

Random File Access Files are normally read from (or written to) sequentially We can move the file position indicator as we wish, though ftell(file_ptr) returns the current value of the file position indicator This value is the number of bytes from the beginning of the file, counting from 0

Moving The File Position Indicator Use fseek() to relocate the file position indicator Syntax: fseek(file_ptr, offset, place); This moves the file position indicator offset bytes from place place can be 0 (file beginning), 1 (current location), or 2 (file end) Note that this is only guaranteed to work correctly with binary files (so add b to the mode, e.g., rb )

Example: Printing File Contents in Reverse Order FILE *ifp = fopen( data.txt, rb ); fseek(ifp, 0, 2); /* go to end of file */ fseek(ifp, -1, 1); /* back up 1 position */ while (ftell(ifp) > 0) { int c = getc(ifp); /* moves ahead 1 space */ putchar(c); fseek(ifp, -2, 1); /* back up 2 positions */ } fclose(ifp);

sprintf() and sscanf() These functions write to, and read from, strings (variables of type char *) rather than the console or a file Their first argument must be of type char * sscanf( 1 2 3 go, %d%d%d%s, &a, &b, &c, tmp); Note that repeated calls to sscanf() restart at the beginning of the source string