Standard C Input/Output. Output: printf() Table of Contents

Similar documents
As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

File Handling. What is a file?

2 ASCII TABLE (DOS) 3 ASCII TABLE (Window)

So far we have considered only numeric processing, i.e. processing of numeric data represented

Module 816. File Management in C. M. Campbell 1993 Deakin University

Informatica e Sistemi in Tempo Reale

System Calls and Standard I/O

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

Pemrograman Dasar. Basic Elements Of Java

C++ Language Tutorial

Illustration 1: Diagram of program function and data flow

Sources: On the Web: Slides will be available on:

The programming language C. sws1 1

C++ Input/Output: Streams

System Calls Related to File Manipulation

Chapter 2: Elements of Java

Variables, Constants, and Data Types

The C Programming Language course syllabus associate level

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Programming Languages CIS 443

Kiwi Log Viewer. A Freeware Log Viewer for Windows. by SolarWinds, Inc.

Tutorial on C Language Programming

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Levent EREN A-306 Office Phone: INTRODUCTION TO DIGITAL LOGIC

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Member Functions of the istream Class

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

5 Arrays and Pointers

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Numbering Systems. InThisAppendix...

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Stacks. Linear data structures

Basics of I/O Streams and File I/O

Chapter One Introduction to Programming

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Crash Dive into Python

CS 106 Introduction to Computer Science I

Fundamentals of Programming

Advanced Bash Scripting. Joshua Malone

Formatting Numbers with C++ Output Streams

Data Storage. Chapter 3. Objectives. 3-1 Data Types. Data Inside the Computer. After studying this chapter, students should be able to:

/* File: blkcopy.c. size_t n

Data Integrator. Pervasive Software, Inc B Riata Trace Parkway Austin, Texas USA

This section describes how LabVIEW stores data in memory for controls, indicators, wires, and other objects.

Introduction to Programming II Winter, 2014 Assignment 2

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

Japanese Character Printers EPL2 Programming Manual Addendum

Chapter 4: Computer Codes

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Lecture 24 Systems Programming in C

The string of digits in the binary number system represents the quantity

Install Java Development Kit (JDK) 1.8

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Embedded Systems Design Course Applying the mbed microcontroller

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Base Conversion written by Cathy Saxton

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Version 1.5 Satlantic Inc.

Simple C Programs. Goals for this Lecture. Help you learn about:

FEEG Applied Programming 5 - Tutorial Session

13 File Output and Input

Number Representation

MarshallSoft AES. (Advanced Encryption Standard) Reference Manual

Introduction to Python

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

C++ Essentials. Sharam Hekmat PragSoft Corporation

2011, The McGraw-Hill Companies, Inc. Chapter 3

DNA Data and Program Representation. Alexandre David

arrays C Programming Language - Arrays

Programming languages C

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

CSI 333 Lecture 1 Number Systems

Computer Programming Tutorial

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

URL encoding uses hex code prefixed by %. Quoted Printable encoding uses hex code prefixed by =.

1 Abstract Data Types Information Hiding

Regular Expression Syntax

How to represent characters?

C PROGRAMMING FOR MATHEMATICAL COMPUTING

.NET Standard DateTime Format Strings

Chapter 1: Digital Systems and Binary Numbers

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

SQL Server An Overview

The C Programming Language

IBM Emulation Mode Printer Commands

Ecma/TC39/2013/NN. 4 th Draft ECMA-XXX. 1 st Edition / July The JSON Data Interchange Format. Reference number ECMA-123:2009

LC-3 Assembly Language

Programming Microcontrollers in C

Transcription:

Standard C Input/Output 1 Output: printf() 2 Table of Contents Output: printf( ) - syntax & sematics Output: printf( ) - examples Output: printf( ) - format control Screen / Printer Control Input: scanf( ) - syntax & sematics Input: scanf( ) - examples Input: scanf( ) - scan sets Considerations: printf( ) & scanf( ) Standard C Files & Functions Standard C File I/O C File I/O Calls File Echo Example Syntax printf ( control string, argument list ) Function Prototype: int printf( const char, *format,... ) ; Semantics returns the number of characters that are output or a negative value if an output error occurs. Argument list expressions are converted according to the corresponding formatter in the control string. Control string formatters are indicated by preceding them with a % symbol. Argument list expressions and control string formatters are matched on a 1-1 basis. Text in the control string that is NOT part of a formatter is output verbatim. Control String Formatters char conversion %d %i decimal integer %u unsigned decimal integer %o unsigned octal integer %x %X unsigned hexadecimal integer %c character %s string or character array %f float %e %E double (scientific notation) %g %G float or double format %% outputs a '%' character 1

Output: printf() - examples 3 Output: printf() - format control 4 Some Examples printf(" sum of %d, %d, and %d is %d\n", 65, 87, 33, 65+87+33); sum of 65, 87, and 33 is 185 printf("character code %c has ASCII code %d.\n", 'A', 'A'); Character code A has ASCII code 65. printf("error %s occurred at line %d \n", emsg, lno); Error invalid variable occurred at line 27 printf("octal form of %d is %o \n", 59, 59); Octal form of 59 is 73 printf("hexadecimal form of %d is %x \n", 59, 59); Hexadecimal form of 59 is 3B printf("square root of 2 is %f \n", sqrt(2.0)); Square root of 2 is 1.414214 printf("square root of 157 is %e \n", sqrt(157.0)); Square root of 157 is 1.252996e+01 printf("you scored %d out of %d for %d%%.\n",17, 25, 68); You scored 17 out of 25 for 68%. Flag Characters Optionally specified between the % and the formatter character field width positive integer giving minimum number of output columns; effect depends upon output type precision period followed by a nonnegative integer giving the minimum number of digits output for (d, i, o, u, x) or the digits to right of decimal point for (e, f) or maximum number of characters for (s) alignment optionally precedes field width; minus sign specifies leftjustification, no minus sign specifies right justification miscellaneous flags plus sign optionally preceding field width specifies that a + character is prefixed to nonnegative numbers pound sign optionally preceding field width specifies that a zero be prefixed to octals and a 0X be prefixed to hexadecimals a zero optionally preceding field width specifies that zeroes are to be used for padding instead of spaces longs & shorts h character optionally preceding field width specifies that a conversion to short int occurs if required prior to output l or L character optionally preceding field width specifies that a conversion to long int or long double respectively occurs if required prior to output 2

Screen / Printer Control Escape Character \ Non-printable (non-displayable) (control) characters may require use of the escape character (backslash) to specify. code control character \n new line \t tab \r carriage return \f form feed \v vertical tab \" double quote \' single quote \\ backslash \a alert (bell) \b backspace whitespace whitespace characters characters blanks, blanks, tabs tabs & newlines newlines Note: some control character s may not be supported by particular device drivers (video cards) monitors/printers. printf() printf() & scanf() scanf() s s are are located located in in the the standard standard I/O I/O library: library: #include #include <stdio.h> <stdio.h> 5 Input: scanf() Syntax scanf ( control string, argument list ) Function Prototype: int scanf( const char, *format,... ) ; Semantics Returns number variables assigned values or EOF if an error. Argument list expressions are pointer expressions converted according to the corresponding formatter in the control string. Standard input file stdin (keyboard) supplys the input stream. Primary differences: printf() / scanf() formatter chars %c specifier can match white space characters in the input. white space characters in the control string (\t \n ) which can match optional white space in the input nonwhite space characters (not %), which must match the next input character in the stream %n causes no input to occur, scanf stores the number of characters read so far by the current scanf() in the corresponding integer pointer argument %% instructs scanf to skip a % sign in the input asterisk character (suppression character * ) preceding a formatter character instructs scanf() to discard the corresponding input data without storing it in a variable e.g., %*c would cause scanf() to discard the next input character Field width specifiers: scanf() inputs multiple characters e.g., %s would cause scanf() to skip white space, read in nonwhite space characters stopping at the next white space character. e.g., %6s causes scanf() to skip white space, read the next 6 nonwhite input characters (stopping at a white space or end of file). e.g., %6c causes scanf() to read the next 6 input characters, including whitespace, (or stopping at end of file). 6 3

Input: scanf() - examples 7 Input: scanf() - scan sets 8 Some Examples scanf( %d%i%i%i%o%x, &a1, &a2, &a3, &a4, &a5, &a6); /* Input echoed as decimal ints */ printf( %d %d %d %d %d, a1, a2, a3, a4, a5, a6); scanf( %e%f%g, &a1, &a2, &a3); /* Input echoed as standard reals */ printf( %f %f %f, a1, a2, a3); scanf( %c%c%s, &c1, &c2, s); /* Input echo */ printf( \ %c%c %s\, c1, c1, s); Input Data 120-120 0120 0x12 120 12 3.1415 0.31415e+01 31.415e-01...into that good night Output 120-120 80 18 80 18 3.1415 3.1415 3.1415...into that good night Set Input Allows for the input of specific sequences of characters Specification Set of characters enclosed in brackets [] Semantics Input stream is read (from the current position), for characters in the scan set, every matched character is appended to the input string, readings stops at the first encountered character that is not in the set. Example scanf( %[.adgihnt printf( \ %s\, Input Data...into that good night Output...int ], s); s); Inverted Scan Sets A circumflex (caret ^) character is placed after the [ bracket. Input stream is read (from the current position), for characters NOT in the scan set, every non-matched character is appended to the input string, readings stops at the first encountered character that is IN the set. e.g., scanf( %[^aeiou], s); 4

Considerations: printf() & scanf() 9 Standard C Files & Functions 10 Complexity Pitfalls printf() & scanf() have options other than those covered herein. knowledge of printf() & scanf() is required to understand legacy C code, but they should be avoided when possible. When reading strings scanf() does not check to determine if the corresponding string variable has enough storage space. It is the programmer s responsibility to ensure that the string variable has enough space allocated. If a string variable does not have the necessary storage, the variable will be filled with input characters, but will not have a null terminating character appended making it an invalid string. Common Errors printf() & scanf() do not check the control string until runtime e.g., printf( %d %d \n ); would most likely cause an execution error printf() & scanf() perform no checking of the argument list e.g., scanf( %ld, &c); attempts to store a long integer into a character may cause a memory protection fault or crash the system. Standard C Files Defined in stdio.h Defines file type: FILE (file pointer) Standard File Functions: fprintf() & fscanf() Prototypes: file purpose connection stdin standard input keyboard stdout standard output monitor stderr standard error monitor int fprintf( FILE *fp, const char *format,...); int fscanf( FILE *fp, const char *format,...); Analogous to printf() & scanf() Equivalent to standard file I/O: fprintf( stdout,... ); «=» printf(... ); fscanf( stdin,... ); «=» scanf(... ); 5

Standard C File I/O File Modes File access (read, write, append) must be specified for each file: mode access "r" reading "w" writing "a" appending "rb" binary reading "wb" binary writing "ab" binary appending multiple concurrent access "mode +" reading & writing Opening & Closing Files Files must be opened before use: FILE *fopen(const char *filename, const char *mode); returns a pointer to the opened file if successful or a NULL pointer upon failure. Files must be closed after use: int fclose(file *stream); returns zero if the file is closed successfully or EOF upon failure. Files opened for reading & writing should be fixed-length record files for efficiency. Between reads/writes a call to fflush() must be made to flush the file buffer or a call to a file position fseek() or fsetpos(). 11 C File I/O Calls Open Close FILE *ifp, *ofp; ifp = fopen( input.txt, r ); ofp = fopen( output.txt, w ); int status; status = fclose(ifp) ; fclose(ofp); // open for reading //open for writing failure to close a file before program termination may result in loss of data at the end of the file due to the file buffer not being flushed. Creation & Deletion A file that does not exist that is opened for writing or appending will be automatically created. A file that does exist that is opened for writing will be automatically overwritten. A file that does exist that is opened for appending will be written to after the end of the file. 12 6

File Echo Example Read & echo a file of SSNs and names 13 #include <stdio.h> main() { int ssn; char FILE name[25]; *customers; if ((customers = fopen( customers.txt, r )) == NULL) printf( * Error: File is inaccessible\n ); else { printf( %-30s%-10s\n, NAME, SSN ); fscanf(customers, %d%s, &ssn, name); while (!feof(customers)) { printf( %-30s%-10s\n, name, ssn); fscanf(customers, %d%s, &ssn, name); } } fclose(customers); return EXIT_SUCCESS; } feof() feof() is is a a boolean boolean that that checks checks end end of of file file status: status: int int feof( feof( FILE FILE *stream) *stream) ; ; 7