UNIT 5 C NOTES
UNIT 5 C NOTES
Types of Files
A file can be classified into two types based on the way the file stores the data.
They are: 1. Text files 2. Binary files
1. Text files
A text file contains data in the form of ASCII characters
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
2. Binary files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII
characters.
They are generally stored with .bin file extension
They can hold higher amount of data, are not readable easily and provides a
better security than text files.
Stream: Stream is a sequence of data bytes, which are used to read and write data
to a file. It is of two types – Input Stream and Output Stream.
Input Stream gets the data from different input devices such as keyboard and
provides input data to the file/program. Output Stream gets the data from the
file/program and write that data on output devices such as monitor or to memory.
Read Mode (r) : Read mode is used to read data from existing file . If the file
doesn't exists already, error occurs
Write Mode (w) : Write mode is used to write data into file. If the file has data
already, it is deleted. New file is created if it doesn't exists already. In write mode, the
cursor is positioned at the beginning of the file.
Append Mode (a) : Append mode is used to append or add data to the existing data
of file. New file is created if it doesn't exists already. In Append mode, the cursor is
positioned at the end of the present data in the file.
c. Processing the file (Input/Output operation on File)
fprintf() : fprintf() is used to write data into a text file. It works just like printf()
except that its first argument is a file pointer. It is used to write data into a file.
Syntax: fprintf (FILE * stream, const char *format …..);
Parameters
str − This is an array containing the null-terminated sequence of characters to
be written.
stream − This is the pointer to a FILE object
fgets( )
This function reads a line from a stream and stores it in a specified string. The
function stops reading text from the stream when either n - 1 characters are read,
the newline character ('\n') is read or the end of file (EOF) is reached.
clrscr();
fputs("This is c programming.", fp);
fclose(fp);
fp = fopen("file.txt" , "r");
if( fgets (str, 60, fp)!=NULL )
{
puts(str);
}
fclose(fp);
getch();
return(0);
}
fputc()
fputc() is used to write a single character at a time to a given file. It writes the given
character at the position denoted by the file pointer and then advances the file
pointer.
This function returns the character that is written in case of successful write operation
else in case of error, EOF is returned.
SYNTAX: fputc(int char, FILE *stream)
Example : fputc(ch, fp)
Parameters
char -- This is character to be written. This is passed as its int promotion.
stream -- This is the pointer to a FILE object.
fgetc()
fgetc() is used to obtain input from a file single character at a time. It returns the
character present at position indicated by file pointer. After reading the character, the
file pointer is advanced to next character. If pointer is at end of file or if an error
occurs, EOF file is returned by this function.
fp = fopen("file.txt","r");
do
{
c = fgetc(fp);
if (feof(fp))
break ;
printf("\n %c", c);
}
while(1);
fclose(fp);
getch();
}
d.Closing a file using fclose() functions
A file needs to be closed after a read or write operation to release the memory
allocated by the program. In C, a file is closed using the fclose() function. This
returns 0 on successful closure and EOF in the case of a failure The fclose()
function is used to close an already opened file. If we fail to close the file before the
program terminates, the operating system will close the file as part of its
housekeeping function.
SYNTAX:-fclose(ptr);
Example:- fclose(fptr);
5.3 Other functions related to files
feof ( ) function :
The feof () function inquires about the end-of-file character (EOF) in a file. If EOF has
been detected, a nonzero value is returned. Otherwise, a value of 0 is returned.
Syntax : feof()
Example:
#include <stdio.h>
int main ()
{
FILE *fp = fopen("test.txt","r");
if (fp == NULL)
return 0;
do
{
c = fgetc(fp);
if (feof(fp))
break ;
printf("%c", c);
}
while(1);
fclose(fp);
return(0);
}
rename() function:
The rename() function change the name of a file to a new one.
Eg :
#include <stdio.h>
int main()
{
char *oldname = "test.txt";
char *newname = "new_test.txt";
if (rename(oldname, newname) == 0)
printf("The file %s was renamed to %s.", oldname, newname);
else
printf("Error renaming the file %s.", oldname);
return 0;
}
remove() function:
The remove() function is be used to delete a file. The function returns 0 if the file is
deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined
inside the <stdio.h> header file.
Syntax : remove("filename");
Eg :
#include <stdio.h>
int main()
{
if (remove("abc.txt") == 0)
printf("Deleted successfully");
else
printf("Unable to delete the file");
return 0;
}
ferror() function:
The ferror() function check for an error in reading from or writing to the given stream. If an I/O
error has occurred, a nonzero value is returned. Otherwise, a value of 0 is returned.
fflush() function:
The fflush() function is used to empty the buffer that is associated with the specified
output stream
fgetpos() function:
The fgetpos() function is used to store the current position of the file pointer that is
associated with stream
ftell() function:
The ftell() function is used to obtain the current value of the file-position indicator for
the stream pointed to by stream.
Reading and writing of a binary file using fwrite() and fread() functions
Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.
fread(): Function fread() also take 4 arguments similar to fwrite() function as above.
Syntax:- fread(address_data,size_data,numbers_data,pointer_to_file);
Example:
fread(&emp, sizeof(emp), 1, fp)
Where,
ptr is a pointer which points to the array which receives structure.
Size is the size of the structure
nst is the number of the structure
fptr is a file pointer.
Example program :
// binary file - reading and writing
#include<stdio.h>
#include<stdlib.h>
# include <conio.h>
int main()
{
struct employee
{
char name[50];
int age;
float salary;
} emp;
FILE *fp;
clrscr();
fp = fopen("employee.txt", "wb");
printf("\nEnter details of employee \n");
printf("\nName: ");
scanf(”%s”,emp.name);
printf("\nAge: ");
scanf("%d",&emp.age);
printf("\nSalary: ");
scanf("%f",&emp.salary);
fwrite(&emp, sizeof(emp), 1, fp);
fclose(fp);
fp=fopen("employee.txt", "rb");
fread(&emp,sizeof(emp),1,fp);
printf("\nEmployee name is %s",emp.name);
printf("\nEmployee age is %d",emp.age);
printf("\nEmployee salary is %.2f",emp.salary);
printf("\nOne record read successfully"); getch();
return 0;
}
OUTPUT:
Enter details of employee
Name: AAA
Age: 22
Salary: 10000
Employee name is AAA
Employee age is 22
Employee salary is 10000.00
One record read successfully
Comparisons:
Sequential files are generally used in cases where the program processes the data
in a sequential order – Eg: reading cassette tape
Random files are generally used in cases where the data should be read or written
at any point in file, rather than having to process it sequentially. Eg: reading CD
A hybrid approach is also possible whereby a part of the file is used for sequential and
part of the file is used to locate something in the random manner in the file.
Sequential access :
Sequential file access is the most straightforward method of accessing files. This
method accesses data as one record at a time by starting from the beginning of the file to
its end. Moreover, the records are read or written in the order they appear in the file. A
common example of sequential access is with a tape drive, where the device must move
the tape's ribbon forward or backward to reach the desired information
Output :
Enter the total numbers
3
Enter the Num:10
Enter the Num:20
Enter the Num:30
the average of numbers is 20.00
#include<stdio.h>
#include<stdlib.h>
struct customer
{
char name[20];
int acct_num;
int acct_balance;
}cust[10];
void main()
{
FILE *fp;
int i,n;
int min=5000;
clrscr();
fp=fopen("accounts.txt","w");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
printf("\n Enter accounts information\n\n");
printf("enter total number of account information");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Name:");
scanf("%s",cust[i].name);
printf("Acct Num:");
scanf("%d",&cust[i].acct_num);
printf("Balance:");
scanf("%d",&cust[i].acct_balance);
fwrite(&cust,sizeof(struct customer),1,fp);
}
fclose(fp);
fp=fopen("accounts.txt","r");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
else
{
printf("\n File opened for reading: accounts.txt\n\n");
}
for(i=0;i<n;i++)
{
fread(&cust,sizeof(struct customer),1,fp); if(cust[i].acct_balance<=min)
{
printf("\n Name=%10s \n Acct Num =%8d \n Balance=%8d",
cust[i].name,cust[i].acct_num,cust[i].acct_balance);
}
}
getch(); fclose(fp);
}
OUTPUT:
Enter accounts information
Enter total number of account information 2
Name: NNN
Acct Num : 1
Balance: 10000
Name : AAA
Acct Num: 2
Balance: 4500
File opened for reading : accounts.txt
Name= AAA
Acct Num=2
Balance=4500.00
Random Access To File
Random access file in C enables us to read or write any data in our disk file without
reading or writing the data before it. ftell() is used to find the position of the file
pointer from the starting of the file. rewind() is used to move the file pointer to the
beginning of the file. There is no need to read each record sequentially , if we want to
access a particular record. C supports the following functions for random access file
processing. These are also called File management functions for random access
1. fseek()
2. ftell()
3. rewind()
fseek():
This function is used for moving the pointer position in the file at the specified byte.
Pointer position:
This sets the pointer position in the file.
Examples:
1. fseek( p,10L, SEEK_SET)
The pointer position is skipped 10 bytes from the beginning of the file.
2. fseek( p,5L, SEEK_CUR)
The pointer position is skipped 5 bytes forward from the current position.
3. fseek(p,-5L, SEEK_CUR)
The pointer position is skipped 5 bytes backward from the current position.
ftell()
This function returns the value of the current pointer position in the file. The value is
counted from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Compare Sequential access and Random access file (or) case study of “How
sequential access file differ from random access file”
fseek() vs ftell()
fseek() vs rewind()
# include <stdio.h>
int main(int argc, char* argv[])
{
int i,n, fact = 1;
printf("No. of arguments = %d",argc);
n = atoi(argv[1]);
// Find the factorial
for (i = 1; i <= n; i++)
{ fact = fact * i; }
printf(" Factorial = %d", fact);
getch();
return 0;
}
OUTPUT:
>> pgm 5
Factorial = 120
C- Files Examples:-
1. Write a C program to read a file and display the content of the file.
#include <stdio.h>
int main ()
{
FILE *fp = fopen("test.txt","r");
if (fp == NULL)
return 0;
do
{
c = fgetc(fp);
if (feof(fp))
break ;
printf("%c", c);
}
while(1);
fclose(fp);
return(0);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\n Name: %s \n Marks=%d \n",name, marks);
}
fclose(fptr);
return 0;
}
3. Write a C program to write all the members of an array of structures to
a file using fwrite(). Read the array from the file and display on the screen.
#include<stdio.h>
#include<conio.h>
struct s
{
char name[50];
int height;
};
int main()
{
struct s a[5],b[5];
FILE *fptr;
int i;
clrscr();
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\n Height: %d", b[i].name,
b[i].height);
}
fclose(fptr);
getch();
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
#include <stdio.h>
# include <conio.h>
int main()
{
FILE *fp;
int line =1, word=1, ch=1;
char c; // To store a character read from file
clrscr();
fp = fopen("b.txt", "r");
rename() int rename ( const char * oldname, const char * The rename() functio
newname ); n change the name of
(or) a file to a new one
rename(“old name”,”new name”);
Q.No Questions
1. Define file. Why are files needed?
2. Mention different type of file accessing.
3. Distinguish between Sequential access and Random access.
4. What is meant by command line argument? Give an example.
5. List out the various file handling function.
6. Compare fseek() and fell() function
7. How to create a file in C?
8. Identify the various file operation modes and their usage.
9. How to read and write the file?
Examine the following:
10. getc() and getchar()
scanf() and fscanf()
Distinguish between following:
11. printf() and fprintf()
feof() and ferror()
12. Mention the functions required for Binary file I/O operations.
13. Identify the different types of file.
14. Identify the difference between Append and Write Mode.
15. What is the use of rewind () functions.
16. What will be the impact if 'fclose()' function is avoided in a file handling C program?
17. Write a C Program to find the Size of a File.
18. Write the Steps for Processing a File
19. Write a code in C to defining and opening a File.
20. Why do we use command line arguments in C?
21. What does argv and argc indicate in command-line arguments ?
22. Compare the terms Field, Record and File.
23. Compare text files and Binary files