Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 13

Universitatea de Vest Timisoara

Facultatea de Matematica si Informatica Programare I

The C programming Language

08.04.21 Lucian Cucu - The C Programming Language 1


Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

I/O models: the UNIX model


Memory
File Control Block
Program
handle
FCB1
open(file_to_read)
n1=open( I/O device 1
... Communication channel 1
read(n1,..)
...

FCB2
Communication channel 2
n2=open(file_to_write)
...
write(n2,..)
...
read(n1,..)
...
Communication: if(eof)
close(file_to_read)
- data (what is being transfered) ...
- control (how the transfer takes place)

I/O models suported by the C standard: I/O device 2


- the Unix model (tolerated)
- the stream model (promoted)
08.04.21 Lucian Cucu - The C Programming Language 2
Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

I/O: the stream model

Memory
File Control Block (FILE structure)
Program
fp1 = fopen(file_to_read)

I/O device 1
... Communication channel 1
fread(fp1,..)
...
(stream)

fread(fp1,..)
...
if(eof)
fclose(fp1)
...

08.04.21 Lucian Cucu - The C Programming Language 3


Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

The stream I/O model: default opened streams

Memory
Program
keyboard

hdd I/O device


stdin

file1
stdout

file2
stderr

display

C:\temp>program < file1 >file2


08.04.21 Lucian Cucu - The C Programming Language 4
Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

I/O: the UNIX model vs the stream model

The UNIX I/O model


- simple & elegant
- safe
- less efficient

The stream I/O model


- complex & flexible
- more efficient (than the UNIX I/O model)
- less safe (requires tight coding discipline)*

*Because the FCB is stored in user memory, as opposed to system meory in the UNIX I/O model!
Any uninitialized pointer might give un-authorized access to the FCB and compromize the data transfer...

08.04.21 Lucian Cucu - The C Programming Language 5


Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

The stream I/O model

Possible I/O actions:

1. operations on files:manage files as an entity (for disk files only)


- remove a file (remove())
- rename a file (rename())
- create a temporary binary file (tmpfile()) which will be removed when closed or at program
termination
- create a unique valid file-name (tmpnam())

2. file access: acces data “inside” a file (apply also to physical devices, not only disk files!)

The basic flow-chart for file-access

- open stream
- manage buffers
- transfer data
- test for potential errors
- handle errors
- get/set position
- close stream

08.04.21 Lucian Cucu - The C Programming Language 6


Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

I/O: text files vs. binary files

Text file:collection of lines of text => the need of end-of-line


Each byte is a character-code! marking!
Aside of the characters which make up the text, the file
contains also the character/characters used to mark the end-of-line. These may vary from
one OS to another!

Binary file: collection of bytes , which represent data (or part of some data!) stored in internal
representation. No extra characters are stored in binary files! This is consistent across all
Operating Systems, except the eventual filling with 0 at the end of the file under some
OSs.
Consequence:
- the text or binary mode should be indicated when opening
- there are specific functions for transfering data to/from a file, according to the mode in
which it was opened

The fopen() function (stream I/O model)

Prototype:
FILE *fopen(char *file_name, char * mode);

FILE – struct type which contains all info needed to control the stream, including the buffers

Typical call: if((fp=fopen(FileName, mode)) == NULL) {/*open failed!...*/ exit(errCode);}


/*transfer data*/
08.04.21 Lucian Cucu - The C Programming Language 7
Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

The stream model: fopen()


Summary of the mode argument
The mode specifies:
- if the file should be opened as a text file (default or 't') or as a binary file ('b')
- the exploitation type: (read - r, write – w, append – a)
- if the file is opened for updating (optional). Updating is indicated by '+'

Text mode
"r" "rt" - open text file in read mode
"w" "wt" - open text file in write mode
"a" "at" - open text file in append mode

"r+" "rt+" "r+t" - open text file in read mode for updating
"w+" "wt+" "w+t" - open text file in write mode for updating
"a+" "at+" "a+t" - open text file in append mode for updating

Binary mode

"rb" - open binary file in read mode


"wb" - open binary file in write mode
"ab" - open binary file in append mode

"rb+" "r+b" - open binary file in read mode for updating


"wb+" "w+b" - open binary file in write mode for updating
"ab+" "a+b" - open binary file in append mode for updating

08.04.21 Lucian Cucu - The C Programming Language 8


Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

The stream model: summary of functions


Input Formatted I/O functions Output

fscanf generic formated I/O functions fprintf

scanf specialized (stdin/stdout) version of fscanf/fprintf printf

sscanf formatted I/O from/to a buffer sprintf

fixed arg-list version of fprintf vfprintf

fixed arg-list version of printf vprintf

fixed arg-list version of sprintf vsprintf

Input Character level I/O functions Output

fgetc generic I/O function to transfer one character fputc

fgets generic I/O function to transfer a read/print a text line fputs

getc macro versions of fgetc/fputc putc

getchar specialized (stdin/stdout) version of fgetc/fputc putchar

gets specialized (stdin/stdout) version of fgets/fputs puts

“send back” to the input one character ungetc


08.04.21 Lucian Cucu - The C Programming Language 9
Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

The stream model: summary of functions


Input Direct I/O functions Output

fread generic I/O for binary files fwrite

Input File positioning functions Output

fgetpos get/set position functions (new style) fsetpos

ftell get/set position functions (old style) fseek

revert to the beginning of the file rewind

Buffer management functions

fflushall
setbuf
setvbuf

Error handling functions

Reset error flag for a given stream clearerror


Test eof flag for a given input stream feof
Test error flag for a given stream ferror
Print the detailed error messge associated with the code in errno perror
08.04.21 Lucian Cucu - The C Programming Language 10
Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

The stream model: position indicators, flags, error codes,…


The current position in the file (and buffer, in case of buffered access) is changed by each call of a transfer or positioning
function. At file open the current position is at the beginning of the file.

Flags are used to indicate the change (or lack of change) of some state. Examples: the error-flag, eof-flag.
Usually the flags are cleared (set to 0). When the state changes (an error occurs or end-of-file is reached after a transfer
function is called the flag is set (1). Testing the flags is possible (and should be done!) by calling specialized functions
(ferror(), feof()) which return the flags value.

Each error is associated to some error code. Whenever an error occurs, the coresponding error-code is placed into a
global variable (errno) which may be used in order to take some action (inform the user about the kind of error)

E.g.
function(fp); /* I/O function which might fail; failure will set the error flag
if(ferror(fp)) /* test the relevant flag for stream fp ; test() might be ferror() or feof()*/
/*handle error; this should include the usage of the current value of errno */
clearerr(fp); /* clear the error flag for the stream to be able to catch next error!*/
...

function(fp); /*any I/O function that changes the file-position indicator */


if( !feof(fp) )/*eof was not reached => a valid data was retrieved!*/
… /* use the retrieved data */
else
fclose(fp); /* eof was reached!)

08.04.21 Lucian Cucu - The C Programming Language 11


Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

Functions with variable-length argument lists


These are functions which might be called with a variable number of arguments:
Declaration:
TYPE function_name(<fixed args declarators>,...);
E.g.
int add(int n,...);
...
sum=add(3, -5, 27, 12); /* sum: 1 fixed arg and 3 args in the var.list*/
printf("the result:"); /* printf: 1 arg */
printf("\t%d\n", sum); /* printf: 2 args */
...
sum=add(2, 257,-25); /* sum: 1 fixed arg and 2 args in the var.list*/
printf("the result:"); /* printf: 1 arg */
printf("\t%d\n", sum); /* printf: 2 args */

printf(“%d%s”,sum,”…is the result!”)

Classes (dependig on the arguments from the variable-length list!):


1. all args are of the same type, at all calls!
2. all args are of the same type at one call; the type of args may change from one call to
another
3. the args of a call may be different

08.04.21 Lucian Cucu - The C Programming Language 12


Universitatea de Vest Timisoara
Facultatea de Matematica si Informatica Programare I

Functions with variable-length argument lists

TYPE f(TYPE1 a, TYPE2 b, ...)


{
va_list ap;
va_start(ap, b);
...
...=va_arg(ap, TYPE3);
...
...=va_arg(ap, TYPE4);
...
...=va_arg(ap, TYPE5);
ap:
va_end(ap);
return address
a:
} Named (fixed) args
b:

Variable length
args list

08.04.21 Lucian Cucu - The C Programming Language 13

You might also like