Title: Input Output
1Input / Output
2General Input and Output
- I/O support is support is provided through
collections of function libraries. - Low level I/O
- open( )
- close( )
- read( )
- write( )
- lseek( )
- ioctl( )
3General Input and Output
- I/O support is support is provided through
collections of function libraries. - Standard library I/O
- fopen( ), fclose( ) - opening and closing
files - fscanf( ), fprintf( ) - field at a time
input/output with
data conversion - fgetc( ), fputc( ) - character (byte) at a
time input/output - fgets( ), fputs( ) - line at a time
input/output - fread( ), fwrite, - physical block at a
time i/o fseek( )
4Files
- The I/O library functions operate on ADT's of
type FILE (which is defined in stdio.h).
5Files
- A collection of related data treated as a unit.
- Two types
- Text
- Binary
- Stored in secondary storage devices.
- Buffer
- Temporary storage area that holds data while they
are being transferred to or from memory.
6Text Files
- Data are stored as human-readable characters.
- Each line of data ends with a newline character.
7Standard Files
- Three special FILE 's are automatically opened
when any program starts - stdin standard input
- Normally associated with the keyboard (but may be
redirected with lt) - stdout (standard output)
- Normally associated with terminal output (but may
be redirected with gt) - Accessed using stdout
- stderr (standard error)
- Normally terminal output
8Standard Files
- stdin, stdout, and stderr are predeclared and
preopened files. - They must not be declared nor opened in your
program.
9User Files
- External files defined by the user
- Must be explicitly opened in the program.
- C assigns a logical name to each external file.
- fopen function
- Prepares a file for processing
- Makes the connection between the external file
and the program. - Creates a program file table to store the
information needed to process the file.
10fopen
- fopen("filename", "mode")
- Filename string that supplies the name of the
file as known to the external world. e.g.
scores.dat
11 Example
- / inOut.c /
- include ltstdio.hgt
- int main(int argc, char argv )
- FILE inFile
- FILE outFile
- int number
- inFile fopen("prog1.dat", "r")
- if(inFile NULL)
- fprintf(stderr, r"input failure. exiting
program\n") - exit(1)
-
- outFile foen("prog1.out", "w")
- if(outFile NULL)
- fprintf(stderr, "output failure. exiting
program") - exit(2)
-
12 Example
- fscanf(inFile, "d", number)
- while (!feof(inFile)
- fprintf(stdout, "d\n", number)
- fprintf(outFile, "d\n", number)
- fscanf(inFile, "d", number)
-
- fclose(inFile)
- fclose(outFile)
- return 0
-
13 fopen
- Always check to make sure the open was
successful. If not, print an error message and
exit. For example, - FILE input fopen("data.dat", "r")
- if(input null)
- fprintf(stdout, "Failure to open file.
Exiting\n") - exit(1)
-
14 fclose
- Used to close a file when no longer needed.
- Prevents associated file from being accessed
again. - Guarantees that data stored in the stream buffer
is written to the file. - Releases the FILE structure so that it can be
used with another file. - Frees system resources, such as buffer space.
15 fclose
- Examples
- fclose(inFile)
- fclose (outFile)
16Formatted Input Functions
- Used to read and convert a stream of characters
and store the converted values in a list of
variables found in the address list. - scanf
- scanf ("format string", address list)
- Reads text data from standard input
- fscanf
- fscanf(fp, "format string", address list)
- Reads input from the specified file.
- fp can be stdin
17Formatted Output Functions
- Display output in human readable form
- printf
- printf ("format string", value list)
- Writes to standard output or standard error file
- fprintf
- fprintf (fp, "format string", value list)
- Writes to the specified file.
- fp can be stdout
18Formatting Input/Output Functions
- Format strings
- Consist of three types of data
- Whitespace
- Text characters
- Field specification
- These may be repeated
19 Field Specification
- Consists of character, a conversion code, and
other formatting instructions. - With one exception (), each field specification
must have a matching parameter in the parameter
list that follows the string. - The type in the field specification and the type
of the parameter must match. - Can have up to six elements for output.
- Can have up to five elements for input precision
is not allowed.
20 Field Specification
- Elements of field specification
- scanf / fscanf
do not store data
h short l long int l double (scan only) L long
double
d, f, c, s, e, E, x, X, i, u, g, G
- left justify
- sign ( or -)
- space if positive
- 0 zero padding
printf / fprintf
21Character Input Functions
- Read one character at a time from a text stream.
- getchar
- int getchar ( )
- Reads the next character from the standard input
stream and returns its value. - Return type is int
22Character Input Functions
- getc and fgetc
- int getc (FILE fpIn)
- int fgetc (FILE fpIn)
- Reads the next character (byte) from the file
stream. - Return type is int
23Character Output Functions
- Write one character (byte) at a time
- putchar
- int putchar (int outChar)
- Writes the parameter to standard output.
- If successful, returns the character written.
24Character Output Functions
- putc and fputc
- int putc (int oneChar, FILE fpOut)
- int fputc (int oneChar, FILE fpOut)
- Write the parameter to the specified file stream.
- If the character is successfully written, the
function returns it.
25Character Input/Output Functions
- While fgetc() and fputc() are fine for building
interactive applications, they are very
inefficient and should never be used for reading
or writing a large volume of data such as a
photographic image file.
26 String Input/Output
- gets
- gets (bufferAddr)
- Takes a line (terminated by a newline) from
standard input. - Converts newline to \0
- If successful, returns the string
27 String Input
- fgets
- fgets (bufferAddr, int buffSize, FILE fp)
- Takes a line (terminated by a newline) from the
specified file pointer. - Puts newline (\n) in the string and appends \0 at
the end of the string - If successful, returns the string
28String Output
- puts
- int puts (buff)
- Takes a null-terminated string from memory and
writes it to standard output. - Changes \0 to \n
29String Output
- fputs
- int fputs (buff, FILE fp)
- Takes a null-terminated string from memory and
writes it to the specified file pointer. - Drops \0
- Programmer's responsibility to make sure the
newline is present at the appropriate place.
30End of File Controlled Loops
- feof
- Function to check if end of file has been
reached. - For an end of file controlled loop
- Read before the loop
- Test for end of file while (!feof(ptr))
- Process
- Read at the bottom of the loop
31Processing Heterogeneous Input Files
- While scanf( ) provides a convenient way to
process input files that have a predefined
format, handling mixed character and numeric
input that do not have a definite format can be
more difficult. - An example of such an input is a .ppm image file.
32Processing Heterogeneous Input Files
- a .ppm image file begins with a header of the
following format - P6
- Program 1
- CpSc 101
- 400 300
- max value for a pixel
- 255
33.ppm Image Files
- Items of useful information in the header include
- P - this is a .ppm file
- 6 - this is a .ppm file containing a color
(as opposed to a grayscale (P5)) image - 400 - the number of columns of pixels in each
row of the image - 300 - the number of rows of pixels in the
image - 255 - the maximum brightness value for a pixel
- Comment lines
- Lines beginning with a are comments
- Any number (including 0) of comment lines
may be present.
34.ppm Image Files
- Example headers
- Example 1
- P6 400 300 255
- Example 2
- P6
- width height
- 400 300
-
- 255
35.ppm Image Files
- Example headers
- Example 3
- P6
- width
- 400
-
- 300
- 255
36Processing Heterogeneous Input Files
- Exercise Write a program that can read general
ppm headers.
37Reading .ppm headers with fgets() and sscanf
- Because of the arbitrary location of comment
lines and the number of comment lines, there is
no obvious way to read the header data using
scanf(). - An alternate approach is to use a combination of
fgets() and sscanf() - sscanf( ) consumes data from a memory resident
buffer instead of consuming data from a file. - sscanf( ) returns the number of items it
successfully consumed from the buffer.
38Reading .ppm headers with fgets() and sscanf
- Suppose the header file consists of the
following - P6 800 600 255
-
39Reading .ppm headers with fgets() and sscanf
- The following program would suffice to read it.
- include ltstdio.hgt
- int main(int argc, char argv )
- char id3 0, 0, 0
- long values3
- char count 0
- char buff256
- FILE inFile fopen("image.ppm", "r")
-
- fgets(buff, 256, inFile)
- id0 buff0
- id1 buff1
- count sscanf(buf2, "d d d",
values1, values2, values3) - fprintf(stderr, "obtained d values\n",
count) - fprintf(stderr, "d d d\n", values1,
values2, values3) - return 0
-
40Reading .ppm headers with fgets() and sscanf
- The preceeding program will not work if the .ppm
header is formatted as follows -
- P6
- comment 1
- 800
- comment 2
- 600 255
- In this case, buff will contain P6\n at line 12
and sscanf() will return 0
41Reading .ppm headers with fgets() and sscanf
- We need a loop that will invoke fgets() to read
a new line of input into buff. - sscanf() will attempt to consume 3 integers from
the buffer. - The loop should end when 3 integers have been
placed in the values array or when there are no
more values to read.
42Block input / output
- fread( ) and fwrite( ) functions are the most
efficient way to read or write large amounts of
data. - fread( ) reads a specified number of bytes from a
binary file an places them into memory at the
specified location. - prototype for fread ( )
- int fread(void pInArea, int elementSize, int
count, FILE fp) - pInArea a pointer to the input area in memory.
- elementSize size of a basic data item, often
specified using the sizeof operator - count number of data items
- fp file pointer of an open file.
- fread( ) returns the number of items read.
43Block input / output
- prototype for fwrite ( )
- int fread(void pOutArea, int elementSize, int
count, FILE fp) - pOutArea a pointer to the output area in
memory. - elementSize size of a basic data item, often
specified using the sizeof operator - count number of data items
- fp file pointer of an open file.
- fwrite( ) copies elementSize count bytes from
the address specified by pOutArea to the file. - fwrite( ) returns the number of items written.
44 fread( ) / fwrite( ) example
- FILE inFile
- int itemsRead
- int count 500
- int data500
- int iteration 0
- inFile fopen(argv1, "r")
- if(!inFile)
- printf("File s failed\n", argv1)
- exit(1)
-
- itemsRead fread(data, sizeof(int), count,
inFile) - while (itemsRead ! 0)
- fwrite(data, sizeof(int), itemsRead,
stdout) - fprintf(stderr, "d d\n, iteration,
itemsRead) - iteration 1
- itemsRead fread(data, sizeof(int), count,
inFile)