Data Files in C - Programming PDF
Data Files in C - Programming PDF
Data Files in C - Programming PDF
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
When you open those files, you'll see all the contents within the file as plain text.
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
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better
security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading data from a file
5. Writing data to a file
FILE *fptr
Opening a file
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
The syntax for opening a file in standard I/O is:
ptr = fopen("filename","mode")
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If the
w Open for writing.
file does not exist, it will be created.
If the file exists, its contents are overwritten. If the
wb Open for writing in binary mode.
file does not exist, it will be created.
Open for append. i.e., Data is added to
a If the file does not exists, it will be created.
end of file.
Open for append in binary mode. i.e.,
ab If the file does not exists, it will be created.
Data is added to end of file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in
rb+ If the file does not exist, fopen() returns NULL.
binary mode.
If the file exists, its contents are overwritten. If the
w+ Open for both reading and writing.
file does not exist, it will be created.
Open for both reading and writing in If the file exists, its contents are overwritten. If the
wb+
binary mode. file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
Open for both reading and appending in
ab+ If the file does not exists, it will be created.
binary mode.
Closing a File
The file (both text and binary) should be closed after reading/writing. Closing a file is
performed using library function fclose().
fclose(fptr); //fptr is the file pointer associated with file to be closed.
Input/output Operation on files
Example.
#include <stdio.h>
#include<conio.h>
int main() {
int i; char ch; FILE *fp;
fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getput.txt", "w"));
if(fp == NULL)
{
printf("Error!");
exit(1);
}
fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getput.txt", "r"));
while((ch=fgetc(fp))!=EOF){
printf(" %c",ch);
}
fclose(fp);
getch();
return 0;
}
Writing File : fputs() function
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax: fputc( str, filepointer). This function writes line of character i.e. str to the
files associated with file pointer.
Example.
#include <stdio.h>
#include<conio.h>
int main() {
int i; char txt[80]; FILE *fp;
fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getputs.txt", "w"));
if(fp == NULL)
{
printf("Error!");
exit(1);
}
fp = (fopen("C:\\Users\\User\\Desktop\\cexamples\\getputs.txt", "r"));
while(fgets(txt,79,fp)!=NULL){
printf("\n %s",txt);
}
fclose(fp);
getch();
return 0;
}
WAP to write line of text to “source.txt” and copy the content of file “source.txt” to
another file “destination.txt” character wise.
#include <stdio.h>
#include<conio.h>
int main() {
int i; char txt[100],ch; FILE *fp1, *fp2;
if(fp1 == NULL)
{
printf("Error!");
exit(1);
}
while((ch=fgetc(fp1))!=EOF){
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
getch();
return 0;
}
Write a C program to read name and marks of n number of students from user and store
them in a file. Display the content of file onto the screen.
#include <stdio.h>
int main(){
char name[50]; int marks, i, num;
FILE *fptr;
fptr = (fopen("C:\\Users\\User\\Desktop\\cexamples\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
}
fclose(fptr);
//getch();
return 0;
}
Reading and writing to a binary file/ unformatted data files
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Whence Meaning
SEEK_CUR Starts the offset from the current location of the cursor in the file.
Ftell(): takes a file pointer & returns a number of type long, that corresponds to the
current position.
Syntax: n=ftell(filepointer);
Rewind(): takes a file pointer and resets the position to the start of the file.
Syntax: rewind(filepointer);
Fseek() Example
1. Fseek(fp, 0, SEEK_SET): go to the beginning of file.
2. Fseek(fp, -m, SEEK_CUR): go backward by m bytes from the current
position.
3. Fseek(fp, 0, SEEK_END): go to the end of the file.
4. Fseek(fp, -m, SEEK_END): go backward by m bytes from the end of file.
//Write a C program to read name age and crn of students from user until user type YES.
//Store these records in a file. Read the content from file and Display onto the screen.
#include <stdio.h>
#include <string.h>
#include <conio.h>
struct Student
{
int age;
char name[30];
int crn;
};
int main()
{
char txt[5];
struct Student s1;
FILE *fptr;
}while((strcmp("YES",txt))==0);
//rewind(fptr);
fseek(fptr, 0, SEEK_SET);
while(fread(&s1,sizeof(s1),1,fptr)>0)
{
printf("\n Name: %s",s1.name);
printf("\n Age:%d",s1.age);
printf("\n Roll Number: %d",s1.crn);
}
fclose(fptr);
getch();
return 0;
}
//Write a C program to read name age and crn of students from user until user type YES.
//Store these records in a file. Read n from the user and display nth record from file.
#include <stdio.h>
#include <string.h>
#include <conio.h>
struct Student
{
int age;
char name[30];
int crn;
};
int main()
{
char txt[5];
struct Student s1;
FILE *fptr;
int n, count=0;
if ((fptr = fopen("C:\\Users\\User\\Desktop\\cexamples\\binary.txt","wb+")) ==
NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
// enter data until user say YES
do
{
printf("\n Enter name: ");
scanf(" %s", s1.name);
}while((strcmp("YES",txt))==0);
//rewind(fptr);
fseek(fptr, 0, SEEK_SET);
while(fread(&s1,sizeof(s1),1,fptr)>0)
{
count ++;
if(n==count)
{
printf("\n Name: %s",s1.name);
printf("\n Age:%d",s1.age);
printf("\n Roll Number: %d",s1.crn);
}
}
fclose(fptr);
getch();
return 0;
}
// program to read the data of employee until the user wishes to stop. Write this data to file.
//Read the data from file, sort the employee based on salary and rank. Finally read the data
//from the file and print the information along rank.
#include<stdio.h>
#include<conio.h>
struct Employee
{
char name[20];
int sal;
int rank;
};
int main()
{
struct Employee e,e1[20],e2[20],temp;
FILE *fp1, *fp2;
int i,j,count=0;
char txt[5];
fp1=fopen("C:\\Users\\User\\Desktop\\cexamples\\employee.txt", "w+");
if(fp1==NULL)
{
printf("Cannot create the file");
exit(1);
}
do
{
printf("\nEnter the name of employee:");
scanf(" %s",e.name);
rewind(fp1);
while(fscanf(fp1," %s %d %d ",e1[count].name,&e1[count].sal,&e1[count].rank)!=EOF)
{
count++;
for(i=0;i<count;i++)
for(j=0;j<count-1;j++)
{
if(e1[j].sal>e1[j+1].sal)
{
temp=e1[j];
e1[j]=e1[j+1];
e1[j+1]=temp;
}
}
fclose(fp1);
fp2=fopen("C:\\Users\\User\\Desktop\\cexamples\\bemployee.txt", "wb+");
if(fp2==NULL)
{
printf("Cannot create the file");
exit(1);
}
fwrite(&e1,sizeof(struct Employee),count,fp2);
rewind(fp2);
fread(&e2,sizeof(struct Employee),count,fp2);
printf("\n\nName\tSalary\tRank\n");
for(i=0;i<count;i++)
{
printf("%s\t%d\t%d \n",e2[i].name,e2[i].sal,e2[i].rank);
}
fclose(fp2);
getch();
return 0;
}
A program behaves abnormally when an error occurs. An unchecked error may result in a
premature termination of program or give incorrect output.
Two status enquiry library functions feof() and ferror() can help us to detect I/O errors in the
files.
feof(): used to test for an end of file condition. It takes a file pointer as an argument and
returns a non-zero integer value if all the data from the specified file has been read and
returns zero otherwise.
if( feof(fp) )
printf(“End of data”);
#here on reading the end of file condition it display the message “End of data”.
ferror(): takes file pointer as its argument and returns an non-zero integer if an error has been
detected up to that point, during processing.
if( ferror(fp) )
printf(“Error has been detected”);
Whenever a file is opened using fopen() function, a file pointer is returned. If the file cannot
be opened for some reason, then the function returns NULL pointer. It can be used to check if
a file been opened or not.
if( fp )
printf(“File cannot be opened.”);