Sei sulla pagina 1di 11

Input and Output

Preview
 Input and output facilities are not part of
the C language itself
 ANSI defines a standard library, including
functions to do
 Input and output
 String handling
 Storage management
 Mathematical routines
 …
Where is the headers of
standard library?
 In Unix system, it is in /usr/include
 Standard headers (.h file)
 Function declarations
 Types declarations
 Macros declarations
<assert.h> <float.h> <math.h> <stdarg.h> <stdlib.h>
<ctype.h> <limit.h> <setjmp.h> <stddef.h> <string.h>
<errno.h> <locale.h><signal.h> <stdio.h> <time.h>
Character input and output
 I/O devices are taken as files

stdin stdout
program

 Input/output redirection
a.out < infile
a.out > outfile
a.out < infile > outfile
a.out < infile | prog2 ch7e1.c
Formatted output - printf
 Prototype
int printf(char *format, arg1, arg2, …)

char string: “…..%f….”

Data type
“…..%-7.5f….”

ch7e3.c
Formatted output - scanf
 prototype
int scanf(char *format, arg1, arg2, …)

No. of matched
items The same as
printf
pointer: provide address
of the variable

ch7e4.c : calculator
Formatted output - scanf
 White space chars are ignored in scanf
ch7e5.c

 What if pointer is not used?


ch7e6.c
File access
 So far, we have learned
 Standard input from keyboard
 Standard output to the screen
 When a C program is started, the OS open
s three files
 stdin
 stdout
 stderr
 Write a program that access a file that i
s not already connected to the program
3 steps to access a file
Library functions
Open a file fopen

Read/write getc, putc


the opened file fread, fwrite
fscanf, fprintf

Close a file fclose


Open a file
Access mode
 Example: Read, write, append
File name
FILE * fp;

fp = fopen(“test.txt”, “r”);
 Purpose: negotiate with the OS, and the OS
returns a file pointer
 FILE: a structure that contains
 Location of a buffer
 Character position in the buffer
 Read or write mode
 Whether end of file have occurred
Example
 cat:
 Concatenate a set of named files onto the
standard output
 Unix command
 catc.c

Potrebbero piacerti anche