Chapter 18 I/O in C Original slides from Gregory Byrd, North Carolina State University Modified slides by C. Wilcox, Y. Malaiya Colorado State University.

Slides:



Advertisements
Similar presentations
CS1061 C Programming Lecture 16: Formatted I/0 A. O’Riordan, 2004.
Advertisements

Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
1 CSE1301 Computer Programming: Lecture 9 Input/Output.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
Programming in C #2 Input / Output.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Chapter 17 - I/O in C. BYU CS/ECEn 124Input and Output2 Concepts to Learn… Standard Libraries Input/Output Data Streams printf() scanf() Variable Argument.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
Chapter 18 I/O in C.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Chapter 3 Input and Output
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
CSE1301 Computer Programming: Lecture 6 Input/Output.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
CS 1704 Introduction to Data Structures and Software Engineering.
Files A collection of related data treated as a unit. Two types Text
CSCI N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Formatted I/O ä ä Standard Output ä ä printf() family of functions ä ä Standard Input ä ä scanf() family of functions.
Introduction to Computing Lecture 03: Basic input / output operations Introduction to Computing Lecture 03: Basic input / output operations Assist.Prof.Dr.
Chapter 9 - Formatted Input/Output
C Formatted Input/Output
Programming in C in a UNIX environment
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Chapter 18 I/O in C.
Introduction to C CSE 2031 Fall /3/ :33 AM.
Input / Output functions in C
Plan for the Day: I/O (beyond scanf and printf)
Programming in C Input / Output.
Input and Output Lecture 4.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Input / Output functions in C
Programming in C Input / Output.
CSI 121 Structured Programming Language Lecture 7: Input/Output
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Chapter 9 - Formatted Input/Output
Chapter 18 I/O in C.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Chapter 18 I/O in C.
Programming in C Input / Output.
Module 12 Input and Output
Introduction to C EECS May 2019.
Chapter 11 Files chap8.
Introduction to C CSE 2031 Fall /15/2019 8:26 AM.
Chapter 18 I/O in C.
Presentation transcript:

Chapter 18 I/O in C Original slides from Gregory Byrd, North Carolina State University Modified slides by C. Wilcox, Y. Malaiya Colorado State University

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 2CS270 - Spring Colorado State University Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented by any ANSI standard implementation. A collection of functions and macros that must be implemented by any ANSI standard implementation. Automatically linked with every executable. Automatically linked with every executable. Implementation depends on processor, operating system, etc., but interface is standard. Implementation depends on processor, operating system, etc., but interface is standard. Since they are not part of the language, compiler must be told about function interfaces. Standard header files are provided, which contain declarations of functions, variables, etc.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 3CS270 - Spring Colorado State University Basic I/O Functions The standard I/O functions are declared in the header file. FunctionDescription putchar Displays an ASCII character to the screen. getchar Reads an ASCII character from the keyboard. printf Displays a formatted string, scanf Reads a formatted string. fopen Open/create a file for I/O. fprintf Writes a formatted string to a file. fscanf Reads a formatted string from a file.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4CS270 - Spring Colorado State University Text Streams All character-based I/O in C is performed on text streams. A stream is a sequence of ASCII characters, such as: the sequence of ASCII characters printed to the monitor by a single program the sequence of ASCII characters printed to the monitor by a single program the sequence of ASCII characters entered by the user during a single program the sequence of ASCII characters entered by the user during a single program the sequence of ASCII characters in a single file the sequence of ASCII characters in a single file Characters are processed in the order in which they were added to the stream. e.g., a program sees input characters in the same order as the user typed them. e.g., a program sees input characters in the same order as the user typed them. Standard input stream (keyboard) is called stdin. Standard input stream (keyboard) is called stdin. Standard output stream (monitor) is called stdout. Standard output stream (monitor) is called stdout.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 5CS270 - Spring Colorado State University Character I/O putchar(c) Adds one ASCII character (c) to stdout. getchar() Reads one ASCII character from stdin. These functions deal with "raw" ASCII characters; no type conversion is performed. char c = 'h';... putchar(c); putchar('h'); putchar(104);... putchar(c); putchar('h'); putchar(104); Each of these calls prints 'h' to the screen.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 6CS270 - Spring Colorado State University Buffered I/O In many systems, characters are buffered in memory during an I/O operation. Conceptually, each I/O stream has its own buffer. Conceptually, each I/O stream has its own buffer. Keyboard input stream Characters are added to the buffer only when the newline character (i.e., the "Enter" key) is pressed. Characters are added to the buffer only when the newline character (i.e., the "Enter" key) is pressed. This allows user to correct input before confirming with Enter. This allows user to correct input before confirming with Enter. Output stream Characters are not flushed to the output device until the newline character is added. Characters are not flushed to the output device until the newline character is added.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 7CS270 - Spring Colorado State University Input Buffering printf("Input character 1:\n"); inChar1 = getchar(); printf("Input character 2:\n"); inChar2 = getchar(); printf("Input character 1:\n"); inChar1 = getchar(); printf("Input character 2:\n"); inChar2 = getchar(); After seeing the first prompt and typing a single character, nothing happens. Expect to see the second prompt, but character not added to stdin until Enter is pressed. When Enter is pressed, newline is added to stream and is consumed by second getchar(), so inChar2 is set to '\n'. When Enter is pressed, newline is added to stream and is consumed by second getchar(), so inChar2 is set to '\n'.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 8CS270 - Spring Colorado State University Output Buffering putchar('a'); /* generate some delay */ for (i=0; i<DELAY; i++) sum += i; putchar('b'); putchar('\n'); putchar('a'); /* generate some delay */ for (i=0; i<DELAY; i++) sum += i; putchar('b'); putchar('\n'); User doesn't see any character output until after the delay. 'a' is added to the stream before the delay, but the stream is not flushed (displayed) until '\n' is added.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9CS270 - Spring Colorado State University Formatted I/O Printf and scanf allow conversion between ASCII representations and internal data types. Format string contains text to be read/written, and formatting characters that describe how data is to be read/written. %d signed decimal integer %f signed decimal floating-point number %x unsigned hexadecimal number %b unsigned binary number %c ASCII character %s ASCII string %d signed decimal integer %f signed decimal floating-point number %x unsigned hexadecimal number %b unsigned binary number %c ASCII character %s ASCII string

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 10CS270 - Spring Colorado State University Special Character Literals Certain characters cannot be easily represented by a single keystroke, because they correspond to whitespace (newline, tab, backspace,...) correspond to whitespace (newline, tab, backspace,...) are delimiters for other literals (quote, double quote,...) are delimiters for other literals (quote, double quote,...) These are represented by the following sequences: \n newline \t tab \b backspace \\ backslash \' single quote \" double quote \0nnn ASCII code nnn (in octal) \xnnn ASCII code nnn (in hex) \n newline \t tab \b backspace \\ backslash \' single quote \" double quote \0nnn ASCII code nnn (in octal) \xnnn ASCII code nnn (in hex)

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 11CS270 - Spring Colorado State University printf Prints its first argument (format string) to stdout with all formatting characters replaced by the ASCII representation of the corresponding data argument. int a = 100; int b = 65; char c = 'z'; char banner[10] = "Hola!"; double pi = ; printf("The variable 'a' decimal: %d\n", a); printf("The variable 'a' hex: %x\n", a); printf("The variable 'a' binary: %b\n", a); printf("'a' plus 'b' as character: %c\n", a+b); printf("A char %c.\t A string %s\n A float %f\n", c, banner, pi); int a = 100; int b = 65; char c = 'z'; char banner[10] = "Hola!"; double pi = ; printf("The variable 'a' decimal: %d\n", a); printf("The variable 'a' hex: %x\n", a); printf("The variable 'a' binary: %b\n", a); printf("'a' plus 'b' as character: %c\n", a+b); printf("A char %c.\t A string %s\n A float %f\n", c, banner, pi);

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 12CS270 - Spring Colorado State University Missing Data Arguments What happens when you don't provide a data argument for every formatting character? printf("The value of nothing is %d\n"); %d will convert and print whatever is on the stack in the position where it expects the first argument. In other words, something will be printed, but it will be a garbage value as far as our program is concerned.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 13CS270 - Spring Colorado State University Reads ASCII characters from stdin, matching characters to its first argument (format string), converting character sequences according to any formatting characters, and storing the converted values to the addresses specified by its data pointer arguments. char name[100]; char name[100]; int bMonth, bDay, bYear; int bMonth, bDay, bYear; double gpa; double gpa; scanf("%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa); scanf("%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa); Scanf( )

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 14CS270 - Spring Colorado State University scanf Conversion For each data conversion, scanf will skip whitespace characters and then read ASCII characters until it encounters the first character that should NOT be included in the converted value. %d Reads until first non-digit. %x Reads until first non-digit (in hex). %s Reads until first whitespace character. Literals in format string must match literals in the input stream. Data arguments must be pointers, because scanf stores the converted value to that memory address.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 15CS270 - Spring Colorado State University scanf Return Value The scanf function returns an integer, which indicates the number of successful conversions performed. This lets the program check whether the input stream was in the proper format. This lets the program check whether the input stream was in the proper format. Example: scanf("%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa); Input StreamReturn Value Input StreamReturn Value Mudd 02/16/ Mudd 02/16/ Muss Muss Doesn't match literal '/', so scanf quits after second conversion.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 16CS270 - Spring Colorado State University Bad scanf Arguments Two problems with scanf data arguments 1. Not a pointer int n = 0; scanf("%d", n); Will use the value of the argument as an address. 2. Missing data argument scanf("%d"); Will get address from stack. If you're lucky, program will crash because of trying to modify a restricted memory location (e.g., location 0). Otherwise, your program will just modify an arbitrary memory location, which can cause very unpredictable behavior.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 17CS270 - Spring Colorado State University Variable Argument Lists The number of arguments in a printf or scanf call depends on the number of data items being read or written. Declaration of printf (from stdio.h): int printf(const char*,...); Recall calling sequence from Chapter 14 Parameters pushed onto stack from right to left. Parameters pushed onto stack from right to left. This stack-based calling convention allows for a variable number of arguments, and fixed arguments (which are named first) are always the same offset from the frame ptr. This stack-based calling convention allows for a variable number of arguments, and fixed arguments (which are named first) are always the same offset from the frame ptr.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 18CS270 - Spring Colorado State University File I/O For our purposes, a file is a sequence of ASCII characters stored on some device. Allows us to process large amounts of data without having to type it in each time or read it all on the screen as it scrolls by. Each file is associated with a stream. May be input stream or output stream (or both!). May be input stream or output stream (or both!). The type of a stream is a "file pointer", declared as: FILE *infile;  The FILE type is defined in.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 19CS270 - Spring Colorado State University fopen The fopen (pronounced "eff-open") function associates a physical file with a stream. FILE *fopen(char* name, char* mode); First argument: name The name of the physical file, or how to locate it on the storage device. This may be dependent on the underlying operating system. The name of the physical file, or how to locate it on the storage device. This may be dependent on the underlying operating system. Second argument: mode How the file will be used: "r" -- read from the file "w" -- write, starting at the beginning of the file "a" -- write, starting at the end of the file (append) How the file will be used: "r" -- read from the file "w" -- write, starting at the beginning of the file "a" -- write, starting at the end of the file (append)

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 20CS270 - Spring Colorado State University fprintf and fscanf Once a file is opened, it can be read or written using fscanf() and fprintf(), respectively. These are just like scanf() and printf(), except an additional argument specifies a file pointer: fprintf(outfile, "The answer is %d\n", x); fprintf(outfile, "The answer is %d\n", x); fscanf(infile, "%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa); fscanf(infile, "%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa);

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. fprintf and fscanf float f1, f2; int i1, i2; int i1, i2; FILE *my_stream; FILE *my_stream; char my_filename[] = "snazzyjazz.txt"; char my_filename[] = "snazzyjazz.txt"; my_stream = fopen (my_filename, "w"); my_stream = fopen (my_filename, "w"); fprintf (my_stream, "%f %f %#d %#d", 23.5, -12e6, 100, 5); fprintf (my_stream, "%f %f %#d %#d", 23.5, -12e6, 100, 5); /* Close stream; skip error-checking for brevity of example */ /* Close stream; skip error-checking for brevity of example */ fclose (my_stream); fclose (my_stream); my_stream = fopen (my_filename, "r"); my_stream = fopen (my_filename, "r"); fscanf (my_stream, "%f %f %i %i", &f1, &f2, &i1, &i2); fscanf (my_stream, "%f %f %i %i", &f1, &f2, &i1, &i2); /* Close stream; skip error-checking for brevity of example */ /* Close stream; skip error-checking for brevity of example */ fclose (my_stream); fclose (my_stream); printf ("Float 1 = %f\n", f1); printf ("Float 1 = %f\n", f1); printf ("Float 2 = %f\n", f2); printf ("Float 2 = %f\n", f2); printf ("Integer 1 = %d\n", i1); printf ("Integer 1 = %d\n", i1); printf ("Integer 2 = %d\n", i2); printf ("Integer 2 = %d\n", i2); 21CS270 - Spring Colorado State University This code example prints the following output on the screen: Float 1 = Float 2 = Integer 1 = 100 Integer 2 = 5 If you examine the text file snazzyjazz.txt, you will see it contains the following text: