Text Output and Input; Redirection

Similar documents
Simple Output and Input. see chapter 7

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

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

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

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

C PROGRAMMING. Characters and Strings File Processing Exercise

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

Organization of a file

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

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

Input / Output Functions

File I/O. Preprocessor Macros

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

Input/Output and the Operating Systems

Course organization. Course introduction ( Week 1)

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

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

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.

EM108 Software Development for Engineers

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

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

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)

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

ENG120. Misc. Topics

CSC 1107: Structured Programming

Programming & Data Structure

CSC 1107: Structured Programming

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

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

CSE 12 Spring 2018 Week One, Lecture Two

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Introduction to file management

Standard File Pointers

CSE 12 Spring 2016 Week One, Lecture Two

C programming basics T3-1 -

C mini reference. 5 Binary numbers 12

UNIX System Programming

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

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

File Handling. 21 July 2009 Programming and Data Structure 1

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

IO = Input & Output 2

Computer Programming Unit v

Standard C Library Functions

Chapter 14 - Advanced C Topics

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

Engineering program development 7. Edited by Péter Vass

Basic and Practice in Programming Lab 10

SWEN-250 Personal SE. Introduction to C

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

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

Procedural Programming

MODULE 3: Arrays, Functions and 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.

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

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

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

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

System Software Experiment 1 Lecture 7

BİL200 TUTORIAL-EXERCISES Objective:

COMP1917: 09 Arrays and Strings

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

Input/output functions

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

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

PROGRAMMAZIONE I A.A. 2017/2018

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

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

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

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

Pointers and File Handling

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

C Basics And Concepts Input And Output

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

Fundamentals of Programming

CS240: Programming in C

Fundamental of Programming (C)

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Operating System Labs. Yuanbin Wu

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

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

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

8. Characters, Strings and Files

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

Library Functions. General Questions

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

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

Computer Science & Engineering 150A Problem Solving Using Computers

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

File Handling. Reference:

Fundamentals of Programming. Lecture 11: C Characters and Strings

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

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING

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

C PROGRAMMING Lecture 6. 1st semester

Transcription:

Text Output and Input; Redirection see K&R, chapter 7 Simple Output puts(), putc(), printf() 1

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). 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. 2

puts() and fputs() Simple Examples 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 3

Character Output Prototypes int fputc(int c, FILE *fileptr); write a single character to a file handle int putc(int c, FILE *fileptr); equivalent to fputc() 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. 4

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; Optional: 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; 5

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 reads input text string from stdin or an opened file. A destination character array must first be created to hold the string. 6

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 - A fgetc() takes a single character but No input is seen until <Enter> is pressed operating system limitation What happens to excess input characters??? 7

fgetc() example - B fgetc() takes only the first character Read additional characters (and discard) until the "newline" is found, or End-Of-Input is reached <Enter> key generates a newline char 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 Instead, copy into a new array of different size 8

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! Don't use gets()! Use fgets() instead fgets() versus gets() First block: fgets() accepts limitedlength text string do-while() loop consumes, displays excess characters Second block: gets() accepts as many characters as offered buffer overflow possible Modern gcc compiler includes error-checks 9

Text strings as parameters in fgets( ), fputs( ) These are both parameters that are strings char the_string[ ] char *the_string these are completely equivalent the length of the argument is unknown, and may change from one function-call to the next Both forms match a supplied character array of any length fputs() expects a NULL at the end (this is something different: char **argv) 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 10

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 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 float strtof(char str[], char **endptr); double strtod(char str[], char **endptr); converts string to float or double endptr as in strtol() 11

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" fgets-gets and Redirection examine input redirected input fgets( ) limits string size gets( ) tries to accept everything 12

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 13