FILES Unit 5
FILES Unit 5
Q) What is file?
A file is a collection of data stored on secondary storage devices such as hard disk.
Files are basically used in real life application involve large amounts of data.
Q) What is Buffer?
A buffer is nothing but a block of memory that is used for temporary storage of data that has to
read from or written to a file.
A stream linked to a disk file is created; a buffer is automatically created and associated with
the stream.
1
2) Opening a file:
A file must be opened before data can be read from or written to it.
In order to open a file we use fopen() function.
Syntax:
fp = fopen( “filename” , “ mode of opening” );
Here fp is a pointer to FILE type and represents a file.
filename is the name of the file being opened (which is remembered by the operating system).
Mode of opening specifies the type of processing that will be done with the file. Mode can be any
one of the following:
mode description
3) Closing a File:-
The file should be closed after reading/writing of a file. Closing a file is performed using
library function fclose().
Syntax: fclose(fp);
Where fp is a pointer to FILE type and represent a file. The file represented by fp is closed.
Q) Explain file I/O functions (OR) explain how to read/write data to a file.
After a file is opened, we can read data stored in a file or write new data onto it depending on the
mode of openings. Standard library supports a good number of functions which can be used for
performing I/O operations.
1) Character Oriented Functions: (fputc() , fgetc()
These are used to read or written characters to a file.
Where c represents a character and fp, a pointer to FILE, represents a file. The function writes the
content of c onto the file represented by fp.
Syntax: c=fgetc(fp);
c is a variable of char type and fp is a pointer to FILE type. The function reads a character from the
file denoted by fp and returns the character value, which is collected by the variable c.
Example:
#include <stdio.h>
void main ()
{
FILE *fp;
char ch=’a’;
clrscr();
fp = fopen("file.txt", "w");
fputc(ch, fp);
fclose(fp);
fp = fopen("file.txt","r");
ch = fgetc(fp);
printf("%c", ch);
fclose(fp);
getch();
}
Syntax: fputs(s,fp);
Where s is a string variable and fp is a file pointer to FILE type. The function writes the string
represented by s to the file pointed to by fp.
Syntax: fgets(s,size,fp);
fprintf(): fprintf() is used to write multiple data items which may ( or not ) be of different types to a file.
Example: fprintf(fp,"%d%s%d",sno,name,fees);
fscanf: fscanf() is used to read mutiple data items which may be of different types from a file.
example: fscanf(fp,"%d%s%d",&sno,&name,&fees);
Example:
#include<stdio.h>
void main()
{
int rno;
char sname[30];
int marks;
FILE *fp;
clrscr();
fp=fopen("student","w");
printf("Enter roll no. register no. name marks\n");
scanf("%d%s%d",&rno,&sname,&marks);
fprintf(fp,"%d\t%s\t%d",rno,sname,marks);
fclose(fp);
fp=fopen("student","r");
fscanf(fp,"%d\t%s\t%d\n",&rno,&sname,&marks);
printf("%d\t%s\t%d\n",rno,sname,marks);
fclose(fp);
4
getch();
}
Syntax: fwrite(buufer_address,size,count,file_pointer);
Here buffer_address is the address of the memory area,the contents of which are to be
written to the file denoted by fourth argument file_pointer.
Size specifies the number of bytes of a block.
Count specifies the number of blocks of data written to the file.
Syntax: fread(buffer_address,size,count,file_pointer);
Here buffer_address is the address of the memory area,the contents of which are to be read
to the file denoted by fourth argument file_pointer.
Size specifies the number of bytes of a block.
Count specifies the number of blocks of data read from the file.
Example:
#include <stdio.h>
#include <string.h>
void main()
{
FILE *fp;
char c[] = "this is c programming";
char buffer[100];
clrscr();
fp = fopen("file.txt", "w ");
fwrite(c, strlen(c) + 1, 1, fp);
fclose(fp);
fp=fopen("file.txt","r");
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);
getch();
}
5
1. Sequentially
2. Randomly
if we want to access the forty fourth record then first forty three record read sequentially to reach forty
four record .In random access data can be accessed and processed directly .There is no need to
read each record sequentially .if we want to access a particular record random access takes less
time than the sequential access.
1) fseek()
2) ftell()
3) rewind()
Where fp is a pointer to FILE type representing a file, offset is the number of bytes by which the
file pointer is to be moved relative to the byte number identified by the third parameter position.
The third parameter position can take one of the following three values 0, 1 and 2.
2. ftell():
The function ftell() returns the current position of the file pointer.
Where fp is a pointer to FILE type representing a file, the current position of the file pointer of the
file is returned by the function.
3.rewind():
The rewind() repositions the file pointer to the beginning of a file.
#include<stdio.h>
#include<conio.h>
struct std
{
int sno;
char regno[10];
6
char sname[10];
int marks;
};
void main()
{
FILE *fp;
int nor,lb;
clrscr();
fp=fopen("student","r");
fseek(fp,0,SEEK_END);
lb=ftell(fp);
printf("The present position of the file pointer is %d\n",lb);
printf("The size of the student structure is %d\n",sizeof(struct std));
nor=lb/sizeof(struct std);
printf("The no of recors=%d\n",nor);
fclose(fp);
getch();
}
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important for
your program especially when you want to control your program from outside instead of hard coding
those values inside the code.
The command line arguments are handled using main () function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to
the program.
#include<stdio.h>
#include<conio.h>
int main(int argc,char *argv[])
{
FILE *fin,*fout;
char c;
if(argv!=3)
{
printf("invalid agruments\n");
exit(1);
}
fin=fopen(argv[1],"r");
fout=fopen(argv[2],"w");
while(!feof(fin))
{
c=fgetc(fin);
fputc(c,fout);
}
fclose(fin);
fclose(fout);
return 0;
7
}
C language does not provide direct support for error handling. However few method and variable
defined in error.h header file can be used to point out error using return value of the function call. In
C language, a function return -1 or NULL value in case of any error and a global variable errno is set
with the error code. So the return value can be used to check error while programming.
C language uses the following functions to represent error
perror() return string pass to it along with the textual represention of current errno value.
strerror() is defined in string.h library. This method returns a pointer to the string representation
of the current errno value.
Example:
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main ()
{
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL)
{
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
}
else {
fclose (pf);
}
return 0;
}
Syntax: remove(“filename”);
Example:
#include<stdio.h>
void main()
{
remove(“file.txt”);
}
8
Renaming a file: The rename() is used to rename a file. It returns 0 if the rename is success
otherwise it returns a nonzero value.
#include <stdio.h>
void main ()
{
int success=0;
success=rename(“file.txt”,”newfile.txt”);
if(success!=0)
printf(“file not renamed\n”);
getch();
}
perror() return string pass to it along with the textual represention of current errno value.
strerror() is defined in string.h library. This method returns a pointer to the string representation
of the current errno value.