Vous êtes sur la page 1sur 47

REVIEW QUIZ

# 1 What data types do the return values o the following functions belong to? a. fopen() b. fgetc() c. fscanf() # 2 Why is the file stdio.h included in programs that use disk files? # 3 What other file input statement is the following statement equivalent to? x = getc (stdin); /* x is char type */ # 4 What is the error in the following statement? fputc (x); */ x is char type */

NIIT

SEM Q/CPR/CR/SESSION 6/1/VER06/95

REVIEW QUIZ (Contd.)


# 5 What happens when the following statement is executed? fputs (Error, stderr); # 6 UNIX supports outputs redirection. What happens when the following command is given at the UNIX prompt: Maniac > newfile and the following lines of the program maniac are executed? fprintf ( stdout, %s, str); fprintf (stderr, %s, errmsg);

NIIT

SEM Q/CPR/CR/SESSION 6/2/VER06/95

REVIEW QUIZ (Contd.)


# 7 Given the following C statement? fp = fopen (saldat, r); What is the error in the following statements? a. file fp; b. fputs (str, fp); c. fgets (alpha, *fp); /* alpha is an array, fp is file pointer */ # 8 State whether true or false. The fgets () function can be used to read data into an array of float type.

NIIT

SEM Q/CPR/CR/SESSION 6/3/VER06/95

REVIEW QUIZ (Contd.)


# 9 A file whose pointer is ptr_to _file has to be created with records containing the following fields: Salesman number Character 4 Name Character 20 The field separator for these records is to be a colon. What command will write data of the appropriate size to the file? Assume that sno and sname are defined as follows: char sno [5], sname [21]; # 10 Can the following command be used to read the records of the file created in # 9? If not, why? fscanf (ptr_to_file, %s %s, sno, sname);
NIIT SEM Q/CPR/CR/SESSION 6/4/VER06/95

SOLUTION TO REVIEW QUIZ


# 1 a. FILE type if successful open (NULL); zero if unsuccessful b. int type (EOF) c. int type (EOF) # 2 FILE is a derived data type and the declaration of this data type is given in the file stdio.h. Since filehandling programs have to use FILE type Pointers, this declaration should be available to the programs. # 3 x = fgetc (stdin); # 4 The file pointer is missing in the fputc () statement. # 5 The string Error is displayed on the standard error device the VDU.
NIIT SEM Q/CPR/CR/SESSION 6/5/VER06/95

SOLUTION TO REVIEW QUIZ (Contd.)


# 6 The output of the first fprint() statement is redirected to the file newfile. The second fprintf() statement prints the contents of the string errmsg on the VDU. This is because the > symbol implies only output redirection. # 7 a. fp has to be declared as a FILE type pointer. b. Since the file has been opened for input (read mode), fputs() cannot be used on the file. c. Invalid parameters-the number of characters to be read is the second parameter. Also, fp should not be preceded by a *.

NIIT

SEM Q/CPR/CR/SESSION 6/6/VER06/95

SOLUTION TO REVIEW QUIZ (Contd.)


# 8 False. (As in the case of gets(), fgets() can read only

into a character array) # 9 fprintf (ptr_to_file, %s:%s, sno, sname); or fprintf (ptr_to_file, %4s20s, sno, sname); # 10 No, fscanf() assumes that the field separator is a white-space.

NIIT

SEM Q/CPR/CR/SESSION 6/7/VER06/95

SPL SESSION
Objectives At the end of this session, you will be able to: Explain how C treats files Write file-handling programs in C using the following functions to open and close files: fopen() fclose() Write file-handling programs in C using the following function for inputs and outputs from files: fgetc() fgets() fscanf() fputc()
NIIT SEM Q/CPR/CR/SESSION 6/8/VER06/95

SPL SESSION (Contd.)


fputs() fprintf() fseek() rewind() Write file-handling programs in C using FILE type pointers State the need for inclusion of the header file stdio.h in file-handling programs Use the exit() function in programs to handle file input errors

NIIT

SEM Q/CPR/CR/SESSION 6/9/VER06/95

FILE HANDLING IN C
File inputs-outputs is similar to input from/to the terminal Files are treated as streams of characters no concept of an indexed or a sequential file

Function are available for single character as well as multiple character input-output from/to files

NIIT

SEM Q/CPR/CR/SESSION 6/10/VER06/95

OPENING FILES
fopen() is used to open files Example #include < stdio.h> main () { FILE *ptr1, *ptr2, *ptr3; ptr1 = fopen (a.dat, r); /* r read mode */ ptr2 = fopen (b.dat, w); /* w write mode */ Ptr3 = fopen (z.dat, a); /* a append mode */ :: }

NIIT

SEM Q/CPR/CR/SESSION 6/11/VER06/95

OPENING FILES (Contd.)


fopen() return FILE type pointer FILE *ptr, ptr2, FILE type declaration in stdio.h < > indicate that stdio.h is in standard UNIX directory-/usr/include

*ptr3;

NIIT

SEM Q/CPR/CR/SESSION 6/12/VER06/95

FILE ACCESS MODES


* The various modes in which a file can be opened are: - read only mode - r - write only mode - w - append mode - a - read + write mode - r+ - write + read mode - w+ - read + append mode - a+

NIIT

SEM Q/CPR/CR/SESSION 6/13/VER06/95

CHARACTER INPUT AND OUTPUT WITH FILES


Functions: fgetc() fputc() (similar to getc()) (similar to putc())

Additional parameter in both function appropriate file pointer while ((c = fgetc (ptr1)) ! = EOF) /*EOF is int type*/ fputc (c, ptr2); fgetc() return an integer value which is type cast into character before being assigned to variable EOF return value is equal to -1

NIIT

SEM Q/CPR/CR/SESSION 6/14/VER06/95

CLOSING FILES
fclose() is used to close files Example # include < stdio.h> main () { : : fclose (ptr1); fclose (ptr2); } Parameter in fclose() is file pointer Each file has to be closed by a separate fclose()
NIIT SEM Q/CPR/CR/SESSION 6/15/VER06/95

MORE ON FILE POINTERS


The NULL Return Value Return by fopen() if it is unsuccessful in opening a file if ((fp = fopen (a.dat, r)) = = NULL Defined in stdio.h Stdin. Stdout and stderr Refer to standard input device (keyboard), standard output device (VDU), standard error device (VDU) fputc (c. stdout); /* to write to VDU */ Defined in stdio.h Not opened in programs

NIIT

SEM Q/CPR/CR/SESSION 6/16/VER06/95

THE exit() FUNCTION


Used to terminate program execution Example if (argc ! = 3) { print (invalid arguments \n); exit (); }

NIIT

SEM Q/CPR/CR/SESSION 6/17/VER06/95

LINE INPUT AND OUTPUT WITH FILES


Function

fgets()
fputs()

(similar to gets())
(similar to puts())

Line length must be known for fgets()

File pointer must be specified for both


while ((fgets (inp, 181, ptr1)) ! = NULL fputs (inp, ptr2); Array size should be greater than line length since fgets() adds NULL character (\ 0)

NIIT

SEM Q/CPR/CR/SESSION 6/18/VER06/95

LINE INPUT AND OUTPUT WITH FILES (Contd.)


Number of character read by fgets() will be:

n 1 (n is number specified in fgets() statement), or


until \ n is encountered

NIIT

SEM Q/CPR/CR/SESSION 6/19/VER06/95

FORMATTED INPUT AND OUTPUT WITH FILES


Function fscanf() fprintf()

(similar to scanf()) (similar to printf())

Additional parameter pointer to the file fscanf() returns number of variables that are actually assigned values after the read; in case of end-of-file return value EOF fscanf() assumes that field separator is any whitespace, I.e. blank character, a tab or a newline

NIIT

SEM Q/CPR/CR/SESSION 6/20/VER06/95

SOME MORE INPUT-OUTPUT FUNCTIONS


fseek Repositions current position on a file opened by fopen() Syntax rtn = fseek (file-pointer, offset, from-where); where: int rtn is the value returned by fseek(); 0 if successful and 1 if unsuccessful FILE file-pointer is pointer returned by fopen() long offset is number of bytes to shift the current position on a file

NIIT

SEM Q/CPR/CR/SESSION 6/21/VER06/95

SOME MORE INPUT-OUTPUT FUNCTIONS (contd.)


fseek (Contd.) int from-where is position on file from where offset would be effective possible positions for affecting the shift in current position are: beginning of file (0) current position (1) end- of-file (2)

NIIT

SEM Q/CPR/CR/SESSION 6/22/VER06/95

SOME MORE INPUT-OUTPUT FUNCTIONS


INSTRUCTION # 1: fp = fopen (DEMOFILE.DAT, r); /* open the file*/ RESULT: 0 1 2 1 2 3 4 5 6 7 8 9 01 2 3 4 5 6 7 8 90

Offset** Offset From Current Position * New Position* -

NIIT

SEM Q/CPR/CR/SESSION 6/23/VER06/95

SOME MORE INPUT-OUTPUT FUNCTIONS


INSTRUCTION # 2: fp = fseek(fp,10L,0); /*shift by 10 bytes from the current position*/ RESULT: 0 1 2 1 2 3 4 5 6 7 8 9 01 2 3 4 5 6 7 8 90

Offset** Offset From Current Position * New Position* 10L Beginning(0) 1 11

NIIT

SEM Q/CPR/CR/SESSION 6/24/VER06/95

SOME MORE INPUT-OUTPUT FUNCTIONS


INSTRUCTION # 3: fp = fgets(buffer,7,fp); /*read (7-1) bytes from current position*/ RESULT: 0 1 2 1 2 3 4 5 6 7 8 9 01 2 3 4 5 6 7 8 90

Offset** Offset From Current Position * New Position* (7-1) Current 11 17 Position

NIIT

SEM Q/CPR/CR/SESSION 6/25/VER06/95

SOME MORE INPUT-OUTPUT FUNCTIONS


INSTRUCTION # 1: fp = fseek(fp,10L,0); /*offset 10 bytes from the beginning of file*/ RESULT: 0 1 2 1 2 3 4 5 6 7 8 9 01 2 3 4 5 6 7 8 90

Offset** Offset From Current Position * New Position* 10L Beginning(0) 7 11

NIIT

SEM Q/CPR/CR/SESSION 6/26/VER06/95

SOME MORE INPUT-OUTPUT FUNCTIONS


rewind() rewind() repositions current position on a file to beginning of file Syntax void rewind (file-pointer); where: FILE * file-pointer is pointer returned by fopen() After rewind() is executed, current position is always 1, i.e. beginning of file

NIIT

SEM Q/CPR/CR/SESSION 6/27/VER06/95

MORE ABOUT THE FUNCTION fopen()


The r + Mode Used to open a file read and write Useful for operations where updation-in-place needs to be performed

NIIT

SEM Q/CPR/CR/SESSION 6/28/VER06/95

MORE ABOUT THE FUNCTION fopen() (contd.)


# include < stdio.h> /* function to read bytes 5 to 10 and increment the data stored in them */ /* this function demonstrates updation-in-place*/ main() { FILE *fp ; char acc_no[5], bal [7]; double f_bal, atof (); long int pos = 4L, offset = 4L; /* for repositioning before read*/ /* open file in read-write mode*/ if((fp = fopen (BALANCE.DAT, r+ )) = = Null); /* open file BALANCE>DAT for read-write*/

NIIT

SEM Q/CPR/CR/SESSION 6/29/VER06/95

MORE ABOUT THE FUNCTION fopen() (contd.)


{ fprintf (stderr, Error opening File, BALANCE.DAT\n); exit(); } while ((fgets (acc_no, 5,fp)) = NULL) */repositon on balance field */ { fgets (bal, 7, fp); /*read field balance */ f_bal = atof (bal) + 100.00 /* convert balance to float and increment by 100*/ sprintf )bal, %6.2, f_bal) /* convert float to a string */ fseek (fp, pos, 0); /* reposition at start of balance*/ fputs (bal, fp); /* field update in place */ pos+ = 10; /* increment position to byte */ number of next balanceSEM Q/CPR/CR/SESSION 6/30/VER06/95 field */

NIIT

MORE ABOUT THE FUNCTION fopen() (contd.)


} fprintf (stdout, The file has been update \ n) fclose (fp) }

NIIT

SEM Q/CPR/CR/SESSION 6/31/VER06/95

SPL EXERCISE
# 1 A utility called hprint has to be written in C, which will allow a user to display, on screen, any number of lines from the beginning of any file. The user has to specify both the number and the file name on the command line in the following format: hprint number file name

The maximum line length is 80 characters. The program should handle possible errors.

NIIT

SEM Q/CPR/CR/SESSION 6/32/VER06/95

SOLUTION TO SPL EXERCISE


# 1 #define MAX 81 #include < stdio.h> main (argc, argv) int argc; char * argv [ ]; inti = 0; char each _ line [ MAX ] ; FILE * PTR; IF (argc != 3) { printf (Invalid number of parameters \ n); exit (); } / * check command line parameters */
NIIT SEM Q/CPR/CR/SESSION 6/33/VER06/95

SOLUTION TO SPL EXERCISE (Contd.)


if (atioi (argv [ 1 ] ) = = 0) { print (Invalid number of parameters \n); exit (); }/* check if first argument is numeric */ if ((ptr = fopen (argv [2], r)) = = NULL ) { printf (Error in opening file \n); exit(); } /*check if file can be opened */ While ((fgets (each_line, MAX,ptr)) != NULL && i < atoi (argv[1])) } i+ + ; printf (%d : ,i);
NIIT SEM Q/CPR/CR/SESSION 6/34/VER06/95

SOLUTION TO SPL EXERCISE (Contd.)


Iprint (each_line,stdout);/* line to be printed and pointer to file on which data is to be written are passed as parameters */ } if (i < atoi (argv [1])) printf (End of file encountered \ n ); /* check if there are lesser number of lines in file than asked for */ } Iprint (to_prin,fp) Char to_print [ ]; FILE * fp; } fputs (to_print,fp); }
NIIT SEM Q/CPR/CR/SESSION 6/35/VER06/95

SPL EXERCISE
#2 Go through the following program called inpcopy.c and its error listing on compilation and then correct the program. 1 # include < stdio.h> 2 main () 3{ 4 file fp; 5 char c; 6 7 fp = fopen (file, w); 8 9 while ((c = fgetc (stdin)) != EOF) 10 fputc (c, fp);
NIIT SEM Q/CPR/CR/SESSION 6/36/VER06/95

SPL EXERCISE
11 12 fclose (fp); 13 } Error listing: inpcopy.c, line 4: file undefined inpcopy.c, line 4: syntax error inpcopy.c, line 7: fp undefined inpcopy.c, line 7: w undefined inpcopy.c, line 7: warning: illegal pointer / integer combination, op = inpcopy.c, line 9: c undefined

NIIT

SEM Q/CPR/CR/SESSION 6/37/VER06/95

SOLUTION TO SPL EXERCISE


#2 # include < stdio.h> main () { FILE*fp; char c; fp = fopen (file, w); while ((c = fgetc (stdin)) != EOF) fputc (c, fp); fclose (fp); }

NIIT

SEM Q/CPR/CR/SESSION 6/38/VER06/95

CLASSROOM EXERCISE
#1 One measure of programming skills in C is whether a programmer is able to simulate UNIX utilities, most of which have originally been written in C itself. As a step towards this, try to program a simplified version of the cut utility, called diffcut, that displays the first field from each record of a file, named on the command line. The utility should assume that the fields are separated by a blank character. The printing of the field from each record should be done through a function. (Assume that the maximum line length is 80 characters)
NIIT SEM Q/CPR/CR/SESSION 6/39/VER06/95

SOLUTION TO CLASSROOM EXERCISE


#1 # define MAXLINE 81 # include < stdio.h> main (argc, argv) int argc; char *argv [ ]; { FILE *fp; char line [MAXLINE]; /* check command line arguments */ if (argc != 2) { printf (Usage : diffcut file-name \ n); exit (); } NIIT SEM Q/CPR/CR/SESSION 6/40/VER06/95

SOLUTION TO CLASSROOM EXERCISE


/* check file status */ if ((fp = fopen (argv [1], r)) = = NULL { printf (File open error \ n); exit (); } /* input line by line from file and display field */ while ((fgets (line, MAXLINE, fp)) != NULL) { printfield (line); printf (\ n:); } }
NIIT SEM Q/CPR/CR/SESSION 6/41/VER06/95

SOLUTION TO CLASSROOM EXERCISE (Contd.)


/* function to display first field from each record */ printfield (record) char record [ ]; { int ind = 0; while (record [ind] != && record [ind] != \0) printf (%c, record [ind+ + ]); }

NIIT

SEM Q/CPR/CR/SESSION 6/42/VER06/95

CLASSROOM EXERCISE
#2 Modify the difficult utility so that it allows any field to be displayed from the file. The number of the field to be displayed should be accepted during execution.

NIIT

SEM Q/CPR/CR/SESSION 6/43/VER06/95

SOLUTION TO CLASSROOM EXERCISE


#2 #define MAXLINE 80 # include < stdio.h> main (argc, argv) int argc; char *argv [ ]; { FILE *fp; char line [MAXLINE + 1]; int fieldnum = 0; /* check command line arguments */ if (argc != 2) { printf (Usage : difficut file-name \ n); exit (); } NIIT SEM Q/CPR/CR/SESSION 6/44/VER06/95

SOLUTION TO CLASSROOM EXERCISE (contd.)


/* check file status */ if ((fp = fopen (argv [1], r)) = = NULL) { printf (File open error \ n); exit (); } /* input field number */ printf (Enter number of field to print : ); scanf (%d, &fieldnum); fflush (stdin);

NIIT

SEM Q/CPR/CR/SESSION 6/45/VER06/95

SOLUTION TO CLASSROOM EXERCISE (contd.)


/* input line by line from file and display field */ while ((fgets (line, MAXLINE + 1, fp)) != NULL) { printfield (line, fieldnum); printf (\ n); } } /* function to display the specified field from each record */ printfield (record, fnum) char record [ ]; int fnum; {
NIIT SEM Q/CPR/CR/SESSION 6/46/VER06/95

SOLUTION TO CLASSROOM EXERCISE (contd.)


int fieldcnt = 1, ind = 0; while (fieldcnt < fnum) { if (record [ind] = = ) fieldcnt+ + ; ind+ + ; } while (record [ind] != ) printf (%c, record [ind+ + ]); }

NIIT

SEM Q/CPR/CR/SESSION 6/47/VER06/95

Vous aimerez peut-être aussi