Sess-6

47
©NIIT SEM Q/CPR/CR/SESSION 6/1/VER06/95 # 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 */ REVIEW QUIZ

Transcript of Sess-6

Page 1: Sess-6

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

# 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 */

REVIEW QUIZ

Page 2: Sess-6

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

# 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 > newfileand the following lines of the program maniac are executed?

fprintf ( stdout, “%s”, str);fprintf (stderr, “%s”, errmsg);

REVIEW QUIZ (Contd.)

Page 3: Sess-6

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

# 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.

REVIEW QUIZ (Contd.)

Page 4: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/4/VER06/95

# 9 A file whose pointer is ptr_to _file has to be created with records containing the following fields:

Salesman number Character 4Name 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);

REVIEW QUIZ (Contd.)

Page 5: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/5/VER06/95

# 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 file- handling 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.

SOLUTION TO REVIEW QUIZ

Page 6: Sess-6

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

# 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 *.

SOLUTION TO REVIEW QUIZ (Contd.)

Page 7: Sess-6

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

# 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.

SOLUTION TO REVIEW QUIZ (Contd.)

Page 8: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/8/VER06/95

ObjectivesAt 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()

SPL SESSION

Page 9: Sess-6

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

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

SPL SESSION (Contd.)

Page 10: Sess-6

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

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

FILE HANDLING IN C

Page 11: Sess-6

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

fopen() is used to open filesExample

#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 */

::}

OPENING FILES

Page 12: Sess-6

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

fopen() return FILE type pointer FILE *ptr, ptr2, *ptr3;

FILE type declaration in stdio.h

< > indicate that stdio.h is in standard UNIX directory-/usr/include

OPENING FILES (Contd.)

Page 13: Sess-6

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

* 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+”

FILE ACCESS MODES

Page 14: Sess-6

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

Functions: fgetc()(similar to getc()) fputc()(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

CHARACTER INPUT AND OUTPUT WITH FILES

Page 15: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/15/VER06/95

fclose() is used to close filesExample

# include < stdio.h>main (){

::

fclose (ptr1);fclose (ptr2);}

Parameter in fclose() is file pointer Each file has to be closed by a separate

fclose()

CLOSING FILES

Page 16: Sess-6

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

The NULL Return Value Return by fopen() if it is unsuccessful in opening a

fileif ((fp = fopen (“a.dat”, “r”)) = = NULL

Defined in stdio.hStdin. 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

MORE ON FILE POINTERS

Page 17: Sess-6

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

Used to terminate program execution

Exampleif (argc ! = 3){

print (“invalid arguments \n”);exit ();

}

THE exit() FUNCTION

Page 18: Sess-6

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

Function

fgets() (similar to gets())

fputs() (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’)

LINE INPUT AND OUTPUT WITH FILES

Page 19: Sess-6

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

Number of character read by fgets() will be:

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

until ’\ n’ is encountered

LINE INPUT AND OUTPUT WITH FILES (Contd.)

Page 20: Sess-6

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

Functionfscanf() (similar to scanf())fprintf() (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 white-space, I.e. blank character, a tab or a newline

FORMATTED INPUT AND OUTPUT WITH FILES

Page 21: Sess-6

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

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 unsuccessfulFILE file-pointer is pointer returned by

fopen()long offset is number of bytes to shift the current position on a file

SOME MORE INPUT-OUTPUT FUNCTIONS

Page 22: Sess-6

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

fseek (Contd.)int from-where is position on file from where offset

would be effectivepossible positions for affecting the

shift in current position are: beginning of file (0) current position (1) end- of-file (2)

SOME MORE INPUT-OUTPUT FUNCTIONS (contd.)

Page 23: Sess-6

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

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

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

SOME MORE INPUT-OUTPUT FUNCTIONS

Page 24: Sess-6

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

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

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

SOME MORE INPUT-OUTPUT FUNCTIONS

Page 25: Sess-6

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

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

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

SOME MORE INPUT-OUTPUT FUNCTIONS

Page 26: Sess-6

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

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

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

SOME MORE INPUT-OUTPUT FUNCTIONS

Page 27: Sess-6

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

rewind() rewind() repositions current position on a file to

beginning of fileSyntax

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

SOME MORE INPUT-OUTPUT FUNCTIONS

Page 28: Sess-6

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

The “r + “Mode Used to open a file read and write

Useful for operations where updation-in-place needs to be performed

MORE ABOUT THE FUNCTION fopen()

Page 29: Sess-6

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

# 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*/

MORE ABOUT THE FUNCTION fopen() (contd.)

Page 30: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/30/VER06/95

{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 balance field */

MORE ABOUT THE FUNCTION fopen() (contd.)

Page 31: Sess-6

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

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

}

MORE ABOUT THE FUNCTION fopen() (contd.)

Page 32: Sess-6

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

# 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.

SPL EXERCISE

Page 33: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/33/VER06/95

# 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*/

SOLUTION TO SPL EXERCISE

Page 34: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/34/VER06/95

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);

SOLUTION TO SPL EXERCISE (Contd.)

Page 35: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/35/VER06/95

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); }

SOLUTION TO SPL EXERCISE (Contd.)

Page 36: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/36/VER06/95

#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;67 fp = fopen (“file”, w);89 while ((c = fgetc (stdin)) != EOF)10 fputc (c, fp);

SPL EXERCISE

Page 37: Sess-6

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

1112 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

SPL EXERCISE

Page 38: Sess-6

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

#2 # include < stdio.h>main (){

FILE*fp;char c;fp = fopen (“file”, “w”);while ((c = fgetc (stdin)) != EOF)

fputc (c, fp);fclose (fp);

}

SOLUTION TO SPL EXERCISE

Page 39: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/39/VER06/95

#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)

CLASSROOM EXERCISE

Page 40: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/40/VER06/95

#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 ();}

SOLUTION TO CLASSROOM EXERCISE

Page 41: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/41/VER06/95

/* 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:);

}}

SOLUTION TO CLASSROOM EXERCISE

Page 42: Sess-6

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

/* 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+ + ]);

}

SOLUTION TO CLASSROOM EXERCISE (Contd.)

Page 43: Sess-6

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

#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.

CLASSROOM EXERCISE

Page 44: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/44/VER06/95

#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 ();

}

SOLUTION TO CLASSROOM EXERCISE

Page 45: Sess-6

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

/* 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);

SOLUTION TO CLASSROOM EXERCISE (contd.)

Page 46: Sess-6

©NIIT SEM Q/CPR/CR/SESSION 6/46/VER06/95

/* 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;{

SOLUTION TO CLASSROOM EXERCISE (contd.)

Page 47: Sess-6

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

int fieldcnt = 1, ind = 0;while (fieldcnt < fnum){

if (record [ind] = = ’ ’) fieldcnt+ + ;

ind+ + ;}while (record [ind] != ’ ’)

printf (“%c”, record [ind+ + ]);}

SOLUTION TO CLASSROOM EXERCISE (contd.)