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.

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Dale Roberts Basic I/O – printf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
S09: I/O Required: PM: Ch 11, pgs Recommended: K&R, Chapter 7 Data Input and Output.
© 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.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
Programming in C #2 Input / Output.
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.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
 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. 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 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.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
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.
File IO and command line input CSE 2451 Rong Shi.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
CSE1301 Computer Programming: Lecture 6 Input/Output.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
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.
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.
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.
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.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
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
Programming in C in a UNIX environment
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
File Access (7.5) CSE 2031 Fall July 2018.
Chapter 18 I/O in C.
Introduction to C CSE 2031 Fall /3/ :33 AM.
Input / Output functions in C
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
Computer Science 210 Computer Organization
CS111 Computer Programming
File Input/Output.
Programming in C Input / Output.
Input and Output Lecture 4.
Computer Science 210 Computer Organization
Input / Output functions in C
Programming in C 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.
Chapter 18 I/O in C.
Programming in C Input / Output.
Module 12 Input and Output
Introduction to C EECS May 2019.
CS1100 Computational Engineering
Introduction to C CSE 2031 Fall /15/2019 8:26 AM.
Professor Jodi Neely-Ritz University of Florida
Chapter 18 I/O in C.
Presentation transcript:

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 Lists File I/O fprintf and fscanf sprintf and sscanf

BYU CS/ECEn 124Input and Output3 C Standard Library Standard libraries promote cross-platform compatibility. Useful for building complex programs. Functions, types, and macros of the standard library are accessed by the #include directive. Headers may be included in any order (and any number of times). Actual I/O libraries can be linked statically or dynamically. Standard Libraries

BYU CS/ECEn 124Input and Output4 ANSI Standard Libraries Diagnostics Character Class Tests Error Codes Reported by (Some) Library Functions Implementation-defined Floating-Point Limits Implementation-defined Limits Locale-specific Information Mathematical Functions Non-local Jumps Signals Variable Argument Lists Definitions of General Use Input and Output Utility functions String functions Time and Date functions Standard Libraries

BYU CS/ECEn 124Input and Output5 Input/Output Most programs require an input and output. I/O is not directly supported by C. I/O is handled by a set of standard library functions defined by the ANSI C standard. The stdio.h header file contains function declarations for I/O and preprocessor macros related to I/O. stdio.h does not contain the source code for I/O library functions! Input/Output

BYU CS/ECEn 124Input and Output6 I/O Data Streams All C character based I/O is performed on streams. All I/O streams must be opened and closed A sequence of characters received from the keyboard is an example of a text stream In standard C there are 3 streams automatically opened upon program execution: stdin is the input stream stdout is the output stream stderr stream for error messages Data Streams

BYU CS/ECEn 124Input and Output7 I/O Data Streams One character at a time: int putc(int character, FILE* stream); #define putchar(c) putc(c,stdout) char c = 'h'; putchar(c); putchar('h'); putchar(104); int getc(FILE* stream); #define getchar() getc(stdin) char c; c = getchar(); Data Streams

BYU CS/ECEn 124Input and Output8 I/O Data Streams On most computer systems, stdin and stdout I/O streams are buffered. A buffer is a temporary storage area Every character sent to the keyboard input stream is captured by the computer’s low-level software and kept in a buffer until it is released to the input stream. Allows editing of typed characters. The keyboard input buffer holds keystrokes until the input line is terminated by the enter (\n) key. After the enter key is pressed, the program can see the characters typed. Data Streams

BYU CS/ECEn 124Input and Output9 Formatted Output The printf function outputs formatted values to the stdout stream using putc printf( const char *format,... ); The format string contains two object types: Ordinary characters that are copied to the output stream Conversion specifications which cause conversion and printing of the next argument in the argument list. printf("\nX = %d, Y = %d", x, y); printf() Conversion specifications Characters

BYU CS/ECEn 124Input and Output10 Formatted Output Each conversion specification begins with a % and ends with a conversion character: Integer"%d" String"%s" Character"%c" Formatting options are inserted between the % and the conversion character: Field width"%4d" Length modifier"%ld" Left justified"%-4d" Zero padded"%04d" printf()

BYU CS/ECEn 124Input and Output11 Formatted Output Common conversion specifications: Decimal"%d" or "%i" String"%s" Character"%c“ Hexadecimal"%x" Unsigned decimal"%u" Floating point"%f" Scientific notation"%e" Pointer"%p" %"%" printf()

BYU CS/ECEn 124Input and Output12 Formatted Output A period is used to separate the field width from the precision when formatting floating point numbers: printf("Speed = %10.2f", speed); A variable field width may be specified using an asterisk (*) formatting option. The value is computed by converting the next argument (which must be an int): printf("%.*s", max, s); printf()

BYU CS/ECEn 124Input and Output13 Formatted Output Variable field width example: printf() #include int main(void) { const char text[] = "Hello world"; int i; for ( i = 1; i < 12; ++i ) { printf("\"%.*s\"\n", i, text); } return 0; } /* my output "H" "He" "Hel" "Hell" "Hello" "Hello w" "Hello wo" "Hello wor" "Hello worl" "Hello world" */

BYU CS/ECEn 124Input and Output14 Formatted Output Certain characters cannot be easily represented by a single keystroke, because they correspond to whitespace (newline, tab, backspace, return...) are used as delimiters for other literals (quote, double quote, backslash,...) special functions \a bell (alert) \n newline \r return \t tab \b backspace \\ backslash \'\' single quote \"\" double quote \0nnn ASCII code – oct \xnnn ASCII code – hex printf()

BYU CS/ECEn 124Input and Output15 Formatted Output int a = 100; int b = 65; char c = 'z'; char banner[ ] = "Hola!"; double pi = ; printf("The variable 'a' decimal: %d\n", a); printf("The variable 'a' hex: %x\n", a); printf("'a' plus 'b' as character: %c\n", a+b); printf("A char %c.\t A string %s\n A float %7.4f\n", c, banner, pi); printf()

BYU CS/ECEn 124Input and Output16 Formatted Output What happens when you don't provide a data argument for every formatting character? printf("\nThe value of nothing is %d"); %d will convert and print whatever is on the stack in the position where it expects to find the first argument. Something will be printed, but it will be garbage or whatever is next in the stack. printf()

BYU CS/ECEn 124Input and Output17 Formatted Input The function scanf is similar to printf, providing many of the same conversion facilities in the opposite direction: scanf( const char *format,... ); reads characters from the standard input (stdin), interprets them according to the specification in format, stores the results through the remaining arguments. The format argument is a string; all other arguments must be a pointers indicating where the corresponding converted input should be stored. scanf()

BYU CS/ECEn 124Input and Output18 Formatted Input Common input conversion specifications: Decimal"%d" or "%i" String"%s" Character"%c“ Hexadecimal"%x" Unsigned decimal"%u" Floating point"%f" scanf()

BYU CS/ECEn 124Input and Output19 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. scanf()

BYU CS/ECEn 124Input and Output20 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. Example: scanf("%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa); Input StreamReturn Value Mudd 02/16/ Muss Doesn't match literal '/', so scanf quits after second conversion. scanf()

BYU CS/ECEn 124Input and Output21 Formatted Input scanf returns the number of successfully matched and assigned input items i = scanf("%d/%d/%d", &mon, &day, &yr); What’s wrong with the following? int n = 0; scanf("%d", n); Of course, the argument is not a pointer! scanf will use the value of the argument as an address What about a missing data argument? scanf("%d"); scanf will get an address from stack, where it expects to find first data argument - if you're lucky, the program will crash trying to modify a restricted memory location. scanf()

BYU CS/ECEn 124Input and Output22 Variable Argument Lists The number of arguments in a call to printf or scanf depends on the number of data items being read or written. Declaration of printf (from stdio.h) int printf(const char*,...); Parameters pushed on the stack from right to left. This stack-based calling convention allows for a variable number of arguments to be easily handled. Variable Argument Lists

BYU CS/ECEn 124Input and Output23 Variable Argument Lists #include #define PRINT_BUFFER_SIZE 32 //************************************************************** //formatted printf to lcd // void lcd_printf(char* fmt,...) { va_list arg_ptr; char pBuffer[PRINT_BUFFER_SIZE]; char* s_ptr = pBuffer; if (strlen(fmt) > PRINT_BUFFER_SIZE) ERROR2(SYS_ERR_PRINT); va_start(arg_ptr, fmt); // create ptr to args vsprintf(s_ptr, fmt, arg_ptr); // create print string while (*s_ptr) lcd_putchar(*s_ptr++); // output string va_end(arg_ptr); // reset ptr to null return; } // end lcd_printf

BYU CS/ECEn 124Input and Output24 I/O from Files The general-purpose versions of I/O routines: printf -> fprintf scanf -> fscanf These general-purpose functions allow us to specify the stream on which they act. Before we can perform file I/O, we need to declare a file pointer for each physical file we want to manipulate: FILE* infile; FILE* outfile; File I/O

BYU CS/ECEn 124Input and Output25 I/O from Files A file stream must be "opened" before acessing Each call to fopen requires two arguments: name of file to open description of mode of operations we want to perform on that file. infile = fopen("myinfile", "r"); outfile = fopen("myoutfile", "w"); File I/O

BYU CS/ECEn 124Input and Output26 I/O from Files The operation modes are: "r" for reading "w" for writing (an existing file will lose its contents) "a" for appending "r+" for reading and writing. If the call to the fopen() function is successful, a file pointer to a logical file is returned. Returns NULL on failed fopen() call FILE* infile; if (infile = fopen("myfile", "r") == NULL) return error; File I/O

BYU CS/ECEn 124Input and Output27 fprintf and fscanf Once a file is opened, it can be read from or written to 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); fscanf(infile, "%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa); fprintf / fscanf

BYU CS/ECEn 124Input and Output28 I/O from Files #define LIMIT 1000 int main() { FILE* infile; FILE* outfile; double price[LIMIT]; int i=0; infile = fopen("myinputfile", "r"); // open for reading outfile = fopen("myoutputfile", "w"); // open for writting if ((infile != NULL) && (outfile != NULL)) { while (i < LIMIT) { if ((fscanf(infile, "%lf", &prices[i]) == EOF)) break; printf("\nprice[%d] = %10.2lf", i, price[i]); //... process prices[i] i += 1; } else printf("\nfopen unsuccessful!"); fclose(infile); fclose(outfile); } File I/O

BYU CS/ECEn 124Input and Output29 I/O from Files #include void filecopy( FILE*, FILE*); int main(int argc, char** argv) { FILE* fp; if (argc == 1) filecopy(stdin, stdout); // use standard I/O else { while (--argc > 0) { if ((fp = fopen(*++argv, "r")) == NULL) { printf("\ncat: can’t open %s", *argv); return 1; } else { filecopy(fp, stdout); fclose(fp); } return 0; } File I/O void filecopy(FILE* ifp, FILE* ofp) { int c; while ((c = getc(ifp)) != EOF) putc(c, ofp); }

BYU CS/ECEn 124Input and Output30 sprintf and sscanf sprintf converts binary numbers to a string int sprintf(char* buffer, const char* fmt,…); buffer – char array big enough to hold converted number(s) fmt – format specification Variable list to be converted Returns number of characters in converted string (not including null character Useful in converting data to strings sscanf converts a string to binary numbers int sscanf(char* buffer, const char* fmt,…); buffer – char array contains data to be converted fmt – format specification List of pointers to variables to hold converted values Returns number of items converted Useful to convert character data files sprintf / sscanf

BYU CS/ECEn 124Input and Output31