Lecture 14
Input and Output
2
Objectives
At the end of this lecture, you would be able to
• Explain the difference between a text file and binary file
• Explain the operations to open a file for various operations and close a file
• Be able to do text, integer and floating point input and output
• Be able to do simple binary file i/o
Read & watch
• English textbook 7 Input and Output, or
• No textbook? Go to tutorialspoint.com – C File I/O
• Video clips at C Programming Tutorials
https://www.youtube.com/playlist?list= PL6gx4Cwl9DGAKIXv8Yr6nhGJ9Vlcjy ymq
– 50, 51, 52
3
Eric Chen 2019-04-28
4
Why learning file i/o?
• The information in main memory is lost when you shutdown the computer
• It is important and necessary to store the data in the secondary storage for future use
• The result from one program can be used by another program, via accessing the secondary storage
5
Data storage
• Data stored in main (primary) memory – dis-appears when you turn off the power
• Data stored in secondary memory
– harddisk, CD, DVD
– data remains even when you turn off the power
– It is useful in practice to save data in the secondary memory for future use
– Data is saved in the form of files
need to learn about files, how to do I/O operations
File concept
• A file is used to store a collection of related information on the secondary memory (disk)
6
• File attributes: name, size, permissions, date stamps
7
File types
• As a programmer, files are classified into 2 types:
• Text file
– contains sequence of characters
– a text editor can manipulate the file
– text encoding is used to encode the characters • Is hello.c a text file?
• Binary file
– Contains sequence of bytes
– Cannot use text editor to manipulate the file
– Special applications required to view and manipulate the binary file
• lecture1.pptx, hello.exe
• In fact, text file is a special case of binary files
8
About input & output in C
• Input and output facilities are not part of the C language itself
– Standard i/O library (stdio) provides the functions for file i/o
• Input and output are very important in applications
– allow you to interact with users
– allow you to store the results in files or read data from files
9
Standard input and output
• stdio.h header file for standard i/o
• Standard input (stdin): keyboard by default
• Standard output (stdout): screen by default
• Standard error (stderr): screen by default
• text input and output
– Text ?
– A text stream consists of a sequence of lines
– each line ends with a newline character (‘\n’) in Linux/Unix systems
– Each line ends with a carriage return (‘\r’) and new line (‘\n’) in MS Windows
10
Read a char from standard input
• Read one char from the standard input (stdin)
int getchar( void );
– it returns the next input character (char code), or EOF when it encounters end of file
– EOF has a vale of -1 and defined in stdio.h
– In MS Windows, in the new line, if you type ctrl-z, it will signal the end of input file
– In Linux/Unix, in the new line, if you type ctrl-d, it will signal the end of input file
print a char to standard output
• Output a char
int putchar( int );
– puts the character given as the argument on the standard output (stdout)
– It returns the character written, or EOF if an error occurs
• Example change-cases.c 11
12
Formatted output–printf
• Details on printf( )
– Printf converts, formats, and prints its arguments on the standard output under control of the format. It returns the number of characters printed.
• The format string contains two types of objects:
– ordinary characters, which are copied to the output stream,
– conversion specifications, each of which causes conversion and printing of the next successive argument to printf.
• Each conversion specification begins with a % and ends with a conversion character
13
Basic printf conversions
• Moreonprintf/scanf,
• Table 7-1
fprintf, sprintf, snprintf
• Similar to printf
– fprintf– Store the output in a file
– sprintf– store the output in a string
– snprintf– store the output in a string with a limit
14
15
Formatted input–scanf
int scanf(char *format, …)
• Analogtoprintf
• scanf reads characters from the standard input, interprets them according to the specification in format, and stores the results through the remaining arguments
• Those arguments must be pointers, indicate where the corresponding converted input should be stored
• It returns the number of successfully matched and assigned input items.
16
sscanf and fscanf
• Same as scanf(), but it reads from a string (sscanf) or from a file (fscanf)
int sscanf(char *string, char *format, arg1, arg2, …) int fscanf(FILE *fp, char *format, …)
17
Basic scanf conversions
18
Disk file access (secondary
storage)
• File – identified by file name
• A disk file should be opened before it can be accessed
• 3 files opened by the operating systems
– stdin – standard input (keyboard)
– stdout– standard output ( screen)
– stderr – standard error ( screen)
• FILE structure is defined in stdio.h and used for the file access
– It contains all information about the file FILE *fp; //define a file pointer variable
19
fopen– prepare for file access
FILE *fp;
FILE *fopen(char *name, char *mode);
• fp is a FILE pointer
• fopen returns a pointer to a FILE structure, and this pointer is then used for accessing the opened file
– NULL is returned, if opening is not successful
• mode, is a character string, indicating how to use the file
– “r” for reading; “w” for writing; “a” for appending – “r+” or “w+” fro reading and writing (updating)
20
Read/write a char from/to a file
int getc(FILE *fp)
• getc returns the next character from the stream referred to by fp; it returns EOF for end of file or error
int putc(int c, FILE *fp)
• putc writes the character c to the file fp and returns the character written, or EOF if an error occurs
21
Close files – fclose( )
• When you do not need to use the files, you should close the files
int fclose(FILE *fp)
• is the inverse of fopen, it breaks the connection between the file pointer and the external name that was established by fopen, freeing the file pointer for another file
• It flushes the output buffer
• When program terminates, all opened files fclose() is called automatically
• You should close the file, if you do not need it any more – number of open files is limited
– if program crashes, the data in the i/o buffer will be lost
22
ferror( ) and feof( )
int ferror(FILE *fp)
• Returns non-zero if an error occurred on the file fp; zero otherwise.
• How do you know that you have read all data from a file ?
int feof(FILE *fp)
• it returns non-zero if end of file has reached on the specified file.
23
Line input from a file
char *fgets(char *line, int maxline, FILE *fp)
• it reads the next input line (including the newline) from file fp into the character array line; at most maxline-1 characters will be read. The resulting line is terminated with ‘\0’.
• Normally fgets returns a line; on end of file or error it returns NULL.
24
Line input from keyboard
char *gets(char *line);
• it reads the next input line from keyboard into the character array line(discarding terminating ‘\n’). The resulting line is terminated with ‘\0’.
• It returns NULL on end of file or error it returns NULL.
• example gets.c
– Observe the difference between gets( ) and fgets( )
25
Problem with gets( )
• Buffer overflow bug is common with gets() char str[50];
printf(“Enter a string : “); gets(str);
• Whenyouentermorethan50characters,the buffer is overflowed bug
• Try the program gets.c to enter more than 50 characters!
– See also in exercises 8 about the bug
• Replace gets( ) with fgets( ) to avoid buffer overflow
26
Line output
int fputs(char *line, FILE *fp)
• fputs writes a string (which need not contain a newline) to a file
• It returns EOF if an error occurs, and non-negative otherwise.
27
puts( )
int puts(const char *s)
• The library function puts is similar to fputs, but operate on stdout.
• It adds new line (‘\n’).
Binary file i/o
• if you do not have a textbook, read binary file i/o at http://www.cprogramming.com/tutorial/cfil eio.html
28
Binary i/o: fread( ) and fwrite( )
• The proto-types: (from manual page gcc)
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the loca‐ tion given by ptr.
The function fwrite ( ) does the write operation to a file.
• Example: textvsbinaryfile.c (also in exercise
14)
29