CO110 Computer Programming13
CO110 Computer Programming13
Files in C
Introduction
Need for files in C
Usually programs consume a large amount of data and
generates information. Now the situation arises where in
we cannot enter the data repeatedly and also we need to
store the generated information permanently.
Output file
Ram site 1 43 % %*()5tyr
djdf kdfd kp
#include<stdio.h>
void main( )
{ FILE *fpt1,*fpt2;
char ch, chp;
fpt1 = fopen("hi", "r");
fpt2 = fopen("hio","w");
if (fpt1 == NULL)
printf("File doesn't exist\n");
else
{ chp = '*';
while ( (ch = getc(fpt1)) != EOF)
{ if(ch != chp) putc(ch,fpt2);
chp=ch;
}
}
fclose(fpt1);
fclose(fpt2);
}
fscanf() and fprintf() functions
The previous file I/O functions can handle only a
single character or integer value at a time. Thus we
have fscanf() and fprintf() functions which can handle
larger and varied data at a time.
The fscanf() can make use of the stdin pointer to read
values from the standard input ( i.e keyboard).
The fprintf() can display the contents of the file to the
standard output(i.e monitor) using the stdout pointer.
The syntax for the functions are
fscanf( ptr, control_ string, argument_list);
fprintf( ptr, control_ string, argument_list);
Write a C progam to read
Employee No.(0 to exit), Name,
Designation, Basic salary and
Grade of Employees and store
this data in a file "emp.dat“.
Display the employee list from
this file.
Employee No.(0 to exit) : 11
Name : Rama Rao M
Desigation : Manager
Basic salary : 34000
Grade :B
Employee No.(0 to exit) : 88
Name : Ajith Holla
Desigation : Asst. Mgr
Basic salary : 24000
Grade :C
Employee No.(0 to exit) : 665
Name : Kiran Ram Yadla
Desigation : Sr. Manager
Basic salary : 45000
Grade :A
Employee No.(0 to exit) : 0
Emp No. Name Designation Grade Basic
------- ----------- ----------- ----- ----- --------
11 Rama Rao M Manager B 34000
88 Ajith Holla Asst. Mgr C 24000
665 Kiran Ram Yadla Sr. Manager A 45000
#include <stdio.h>
main()
{ int empno, basic, da, hra, gs, pf, ptax, ns;
FILE *emp;
char desig[15], name[25], grade;
emp = fopen("emp.dat","w");
while(1)
{ printf (" Employee No.(0 to exit) : ");
scanf("%d", &empno);
if(empno==0) break;
printf("Name : ");
scanf(" %[^\n]",name);
printf("Desigation : ");
scanf(" %[^\n]",desig);
printf("Basic salary : ");
scanf("%d",&basic);
printf("Grade :");
scanf(" %c",&grade);
fprintf(emp,"%d %s\n%c %d %s\n", empno, name,
grade, basic, desig);
}
fclose (emp);
emp =fopen("emp.dat","r"); //same file is opened again
// with same file pointer variable
printf("Emp No. Name Designation Grade
Basic\n");
printf("------- ----------- ----------- ----- -----
\n");
while( !feof(emp) )
{ fscanf(emp,"%d %[^\n]\n%c %d %[^\n]\n",
&empno, name, &grade, &basic, desig);
printf(" %3d\t %-20s %-15s%c %5d\n",
empno, name, desig, grade, basic);
}
}
Standard Error
Standard error (stderr)is a file pointer where we display error
messages.
fprintf(stderr, "Can't open input file !\n");
#include <stdio.h>
#include <stdlib.h>
main()
{ FILE *fp; char name[80]; int age, n, i=0;
if((fp=fopen("test.txt","w"))==NULL)
{ printf("Cannot open file.\n");
exit(1);
}
printf("How many employees");
scanf("%d",&n);
while(i++<n)
{ printf("Enter the name and age: ");
fscanf(stdin,"%s%d",name,&age);//read from kboard
fprintf(fp,"%s %d",name,age);//write to file
}
fclose(fp);
if((fp=fopen("test.txt","r"))==NULL)
{ printf("Cannot open file.\n");
exit(1);
}
while( !feof(fp))
{ fscanf(fp,"%s%d",name,&age);// read from file
fprintf(stdout,"%s %d\n",name,age);
// print on screen
}
}
Errors which occur during file I/0 operations
Trying to read beyond end-of-file (EOF)
Trying to use a file that has not been
opened
Perform operation on file not permitted by
the fopen mode i.e. attempting a write using
a file pointer opened using a read mode
Open a file with an invalid filename
Attempting a write to a write-protected file
Error Handling in Files
feof() takes file-pointer as input.
returns nonzero (true) if all data read
returns zero (false) otherwise
if(feof(fp))
printf(“End of data\n”); feof() is a function
whereas EOF is a constant
575025
NIT
This is a
long sen
tence whi
ch may no
t fit in
all strin
gs.
This is t
he end
Bye
#include <stdio.h>
int main()
{ FILE * pFile;
char mystring [100];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) printf("Error opening file");
else
while(fgets (mystring, 20, pFile) != NULL )
puts(mystring);
fclose (pFile);
}
Output
NITK SURATHKAL MANG
ALORE
575025
NIT
Bye
#include <stdio.h>
int main()
{ FILE * pFile;
char mystring [100];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) printf("Error opening file");
else
while(fgets (mystring, 10, pFile) != NULL )
printf(“%s”,mystring);
fclose (pFile);
}
output
NITK SURATHKAL MANGALORE
575025
NIT
This is a long sentence which may not fit in all strings.
This is the end
Bye
Random access to files
Till now we have seen a sequential manner in which we can
access files, which is either from the beginning of the
file(read/write modes) or from the end of the file(append
modes).
The question which arises is how to jump to a given position
(byte number) in a file without reading all the previous data?
$ cc program.c
$ ./a.out I study @ NITK
NITK
@
study
I
$
Write a program to display
the factorial of a given integer
using command line
arguments.
cmdlnfct 3
Fact 6
cmdlnfct
Enter the integer 4
Fact 24
/* Command line arguments for Factorial */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main(int argn,char *argc[ ])
{ int n, f=1;
if (argn==1) /*If The input number is not given at command
line */
{ printf("Enter the integer");
scanf("%d",&n);
}
else n= atoi(argc[1]); /* convert string to integer */
while(n) f *=n--;
printf("Fact %d",f);
}
Why do we require Files in C ? Also explain in detail
the different types of Files.
Explain the fopen() with the different modes it utilizes
Write short notes on the following file functions
fclose() getc() putc() getw() putw()
Write short notes on the File random access functions
available in C
What are Command Line arguments? Explain with a
suitable program