Simple Output and Input. see chapter 7

Similar documents
Text Output and Input; Redirection

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

File IO and command line input CSE 2451

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

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);

C PROGRAMMING. Characters and Strings File Processing Exercise

Input / Output Functions

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

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

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

Input/Output and the Operating Systems

Standard File Pointers

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

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

EM108 Software Development for Engineers

Organization of a file

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

File I/O. Preprocessor Macros

Course organization. Course introduction ( Week 1)

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

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

CSC 1107: Structured Programming

CSC 1107: Structured Programming

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

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

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

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

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

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)

COMP1917: 09 Arrays and Strings

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

ENG120. Misc. Topics

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

C programming basics T3-1 -

C mini reference. 5 Binary numbers 12

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Programming & Data Structure

Computer Programming Unit v

Standard C Library Functions

Chapter 8: Character & String. In this chapter, you ll learn about;

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

Basic and Practice in Programming Lab 10

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

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

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

System Software Experiment 1 Lecture 7

Fundamentals of Programming

UNIX System Programming

Fundamental of Programming (C)

MODULE 3: Arrays, Functions and Strings

Advanced C Programming Topics

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

Input/output functions

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

BİL200 TUTORIAL-EXERCISES Objective:

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

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

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Introduction to file management

Engineering program development 7. Edited by Péter Vass

Computer Science & Engineering 150A Problem Solving Using Computers

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

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

CSE 12 Spring 2018 Week One, Lecture Two

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

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

CSE 303 Lecture 15. C File Input/Output (I/O) reading: Programming in C Ch. 16; Appendix B pp

Binghamton University. CS-220 Spring Includes & Streams

SWEN-250 Personal SE. Introduction to C

CSE 12 Spring 2016 Week One, Lecture Two

Lecture 4. Console input/output operations. 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

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

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Should you know scanf and printf?

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

A Short C Primer. Charles E. Campbell, Jr., PhD. January 5, Introduction 1

IO = Input & Output 2

Pointers and File Handling

PROGRAMMAZIONE I A.A. 2017/2018

Introduction. Files. 3. UNIX provides a simple and consistent interface to operating system services and to devices. Directories

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

File Handling. 21 July 2009 Programming and Data Structure 1

Procedural Programming

Operating System Labs. Yuanbin Wu

8. Characters, Strings and Files

C Basics And Concepts Input And Output

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Chapter 14 - Advanced C Topics

Fundamentals of Programming. Lecture 11: C Characters and Strings

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Arrays, Strings, & Pointers

C PROGRAMMING Lecture 6. 1st semester

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

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

For Your Amusement. Beware of bugs in the above code; I have only proved it correct, not tried it. Donald Knuth. Program Verification

Homework 2 Answers. Due Date: Monday, April 29, 2002, at 11:59PM Points: 100

SAE1A Programming in C. Unit : I - V

File Handling. Reference:

Transcription:

Simple Output and Input see chapter 7

Simple Output puts(), putc(), printf()

Simple Output The simplest form of output is ASCII text. ASCII occurs as single characters, and as nullterminated text strings arrays of characters with an ASCII 0 at the end. Functions write to stdout, or to a file specified by a file handle (FILE * type).

puts() and fputs() Simple Example

String output Functions Prototypes int puts(char s []) ; s is the null-terminated text string to be printed A newline is printed after the string. int fputs(char s [], FILE *fileptr) ; s is the null-terminated text string to be printed No newline at end string must include it if desired. fileptr is the destination e.g. stdout These functions return a non-negative number, or EOF to indicate an error.

Alternate Ways of Writing Arguments These forms are equivalent: int puts(char s []) ; int puts(char *s ) ; So are these: int fputs(char s [], FILE *fileptr) ; int fputs(char *s, FILE *fileptr) ; Both forms are used interchangeably sometimes the choice depends on how the argument will be used in the function

Character Output Prototypes int putc(int c, FILE *fileptr); equivalent to fputc() int fputc(int c, FILE *fileptr); write a single character to a file handle int putchar(int c); equivalent to fputc(c, stdout) These functions return the character that was written, or EOF to indicate failure.

An Alternative printf() printf() is another output function Much more versatile More complex It can be used like puts(), but it won't add a newline. int printf(char s []) ; Returns the number of characters printed, or a negative number on error. There is much more to printf() than this, but it can be used this way.

What if you want numeric output? The numbers to be displayed must be converted to text strings. printf() does this More on this later. but here's a taste: printf( "%d", integer); printf( "%f", float_or_double);

activity /*random outputs*/ #include <stdio.h> #include <stdlib.h> // for random() int main(int argc, char** argv) { unsigned ri; float rf; Use time.h to initialize the PRNG. Add a loop to print out multiple random numbers. srandom(1); ri = random(); rf = 1.0 * ri / RAND_MAX; printf("%u %f\n", ri, rf); } return 0;

Simple Input fgets() also, gets()

Simple Input A single ASCII character is the simplest input. fgetc(), getc(), getchar() functions read and return a character from stdin or an opened file. ungetc() function allows inspecting a character "before" getting it Text strings can be built from individual characters, or read in all at once. fgets() function read input from stdin or an opened file. A destination character array must first be created to hold the string.

Character Input Prototypes int fgetc(file *fileptr); read a single character from a file handle int getc(file *fileptr); equivalent to fgetc() int getchar(void); equivalent to fgetc(stdin) int ungetc(int c, FILE *fileptr); pushes character c back into the input stream's buffer (but not back into stdin or the file) These functions return the character read, or EOF to indicate failure.

fgetc() example fgetc() takes a single character but No input is seen until <Enter> is pressed operating system limitation

Text-string input first, a word on text strings There is no "text string" type! Newer, bigger languages add the type C "text string" is an array of characters declared as e.g. char mystring [20] ; // 20-character array C terminates text strings with a NULL character (ASCII 0) that occupies one space Terminating NULL is stored in the array along with the other characters So mystring can only hold 19 "usable" characters Once created, an array cannot be resized

String Input Function Prototype int fgets(char *s, int size, FILE *fileptr) ; s points to the destination text string size is the maximum #of characters to accept accepts one less, to leave space for terminating null fileptr is the source e.g. stdin returned text includes any newline at end Old function: int gets(char *s) ; Final newline is removed NO checking for too many characters! gets() is deprecated; use fgets() instead

fgets() versus gets() First block: fgets() accepts limited-length text string do-while() loop consumes, shows excess characters Second block: gets() accepts as many characters as offered buffer overflow possible Modern gcc compiler includes error-checks

fgets() gets() analyzed Fill member s.b with some text, show it fgets() limits s.dest size structs are like classes that have no methods Create a struct Chars object do-while() absorbs excess gets() overfills s.dest, steps on s.b nothing left to absorb

What if you need numeric input? C has functions that convert a string into a number. Apply as needed to the input from fgets(). No error-checking these expect the string to "look like" a proper number. "ASCII-to-number" functions are simple; do no error-checking "STR-to-number" functions are more versatile; more effort to use

ASCII-to-number Functions int atoi(char str[]); converts ASCII to a signed integer long atol(char str[]); converts ASCII to a signed long integer long long atoll(char str[]); converts ASCII to signed long long integer non-standard double atof(char str[]); converts ASCII to a double-precision floating-point integer used for floats and doubles

float strtof(char str[], char **endptr); double strtod(char str[], char **endptr); converts string to float or double endptr is set to point to where the conversion ended in the supplied string STR-to-number Functions long strtol(char str[], char **endptr, int base); converts string to signed long integer, assuming the given base (0 means "try to guess") endptr is set to point to where the conversion ended in the supplied string unsigned long strtoul(char str[], char **endptr, int base); like strtol(), but converts to unsigned long

comparable to printf() see 7.4 scanf() formatted inputs

scanf() Alternative to reading a string and converting Uses a format specifier, like printf() does Simple usage for numeric inputs: scanf(" %d", &int_variable); scanf(" %c", &char_variable); scanf(" %f", &float_variable); ^ ^ The space helps in the format specifier The ampersand is important in on the variable name but NOT needed for inputting character strings

More scanf() details s canf() can read more than one item at a time use this to "parse" an input line scanf()'s return value shows how many items are successfully read Return value is "EOF" (End Of File) if error occurs, such as wrong data type (string input instead of expected number) Single whitespace in format-specifier string handles variable whitespace in inputs including no whitespace when field lengths are specified Always specify a maximum length when reading string inputs! Otherwise you risk a buffer overflow, as with gets()

Multiple inputs From one scanf() No "&" used for char-string arguments spaces in format-specifier Maximum field width is given

Command-Line Redirection Standard I/O functions read from/write to the console i.e. the screen and keyboard These can be redirected from/to text files Use "<" and ">" for input/output redirection Input:./myprog < datafile.txt All standard inputs come from "datafile.txt" End of file causes EOF Output:./myprog > results.txt All standard outputs get saved in "results.txt"

Finally What if you DON'T use input redirection, but your program is looking for the EOF character? Using up the file generates EOF, but there is no file keyboard input can continue indefinitely Generate an EOF on the keyboard by entering "^D" (ctrl-d) on a line by itself This is different from ^D stored in a file, where it is a carriage-return character Windows/DOS: use ^Z instead of ^D