Posts Tagged file handling
Write a programe that display size of a file in bytes.
Posted by admin in C Examples on November 4th, 2009
#include<stdio.h>
main()
{
int c,sum=0,n=0;
char str[20];
FILE *fin;
puts("Enter the file name::");
gets(str);
fin=fopen(str,"r");
if(fin==NULL)
{
puts("\nsError while opening file.");
exit(0);
}
while((c=fgetc(fin))!=EOF)
n++;
fclose(fin);
printf("Size of file is:: %d\n", n);
}
Write a program that takes a file as an argument and counts the total number of lines. Lines are defined as ending with a newline character.
Posted by admin in C Examples on November 4th, 2009
#include<stdio.h>
main()
{
int c,l=0;
char str[20];
FILE *fin;
puts("Enter the file name::");
gets(str);
fin=fopen(str,"r");
if(fin==NULL)
{ printf("\nError while opening.");
exit(0);
}
else { do{c=getc(fin);
if(c=='\n') l++;
}while(c!=EOF);
fclose(fin);
printf("\nTotal number of lines:: %d\n",l);
}
}
Program to reverse the first n characters in a file in C.
Posted by admin in C Examples on August 7th, 2009
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <process.h>
void main(int argc, char *argv[])
{
char a[15];
char s[20];
char n;
int k;
int j=0;
int i;
int len;
FILE *fp;
if(argc!=3)
{
puts("Improper number of arguments.");
exit(0);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
puts("File cannot be opened.");
exit(0);
}
k=*argv[2]-48;
n = fread(a,1,k,fp);
a[n]='\0';
len=strlen(a);
for(i=len-1;i>=0;i--)
{
s[j]=a[i];
printf("%c",s[j]);
j=j+1;
}
s[j+1]='\0';
getch();
}
Program which copies one file to another in C.
Posted by admin in C Examples on August 7th, 2009
#include <stdio.h>
#include <conio.h>
#include <process.h>
void main(int argc, char *argv[])
{
FILE *fs,*ft;
char ch;
clrscr();
if(argc!=3)
{
puts("Invalid number of arguments.");
exit(0);
}
fs = fopen(argv[1],"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
exit(0);
}
ft = fopen(argv[2],"w");
if (ft==NULL)
{
puts("Target file cannot be opened.");
fclose(fs);
exit(0);
}
while(1)
{
ch=fgetc(fs);
if (ch==EOF)
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
getch();
}
Program to merge two files in C.
Posted by admin in C Examples on July 5th, 2009
#include<stdio.h>
main()
{
char f1[10],f2[10];
puts("enter the name of file 1"); /*getting the names of file to be concatenated*/
scanf("%s",f1);
puts("enter the name of file 2");
scanf("%s",f2);
FILE *fa,*fb,*fc;
fa=fopen(f1,"r"); /*opening the files in read only mode*/
fb=fopen(f2,"r");
fc=fopen("merge.txt","w+"); /*opening a new file in write,update mode*/
char str1[200];
char ch1,ch2;
int n=0,w=0;
while( (( ch1=fgetc(fa) )!=EOF)&&((ch2=fgetc(fb))!=EOF))
{
if(ch1!=EOF) /*getting lines in alternately from two files*/
{ ungetc(ch1,fa);
fgets(str1,199,fa);
fputs(str1,fc);
if(str1[0]!='\n') n++; /*counting no. of lines*/
}
if(ch2!=EOF)
{ ungetc(ch2,fb);
fgets(str1,199,fb);
fputs(str1,fc);
if(str1[0]!='\n')n++; /*counting no.of lines*/
}
}
rewind(fc);
while((ch1=fgetc(fc))!=EOF) /*countig no.of words*/
{
ungetc(ch1,fc);
fscanf(fc,"%s",str1);
if(str1[0]!=' '||str1[0]!='\n')
w++;
}
fprintf(fc,"\n\n number of lines = %d \n number of words is = %d\n",n,w-1);
/*appendig comments in the concatenated file*/
fclose(fa);
fclose(fb);
fclose(fc);
}
Program for printing file contents on standard output which are passed as command line argument
Posted by admin in C Examples on June 27th, 2009
#include <stdio.h>
void putfile(FILE *);
int main(int argc,char *argv[])
{
FILE *fp;
int i=1;
if(argc>1)
{
while(--argc)
{
if((fp=fopen(argv[i++],"r"))==NULL)
{
fprintf(stderr,"can't open %s \n",argv[i-1]);
continue;
}
putfile(fp);
fclose(fp);
}
}
else putfile(stdin);
}
void putfile(FILE *fp)
{
int ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
}
program for reading records from one file and writing them to another file in ‘pipe seperated fields’ format
Posted by admin in C Examples on June 27th, 2009
fclose(fp2);#include<stdio.h>
#define MAXLINE 80
#define NAMELEN 25
pad(char *s,int len)
{
for(;*s && len;s++,len--);
for(;len;len--)
*s++=' ';
*s='\0';
}
int main()
{
FILE *fp1,*fp2;
int eno,eage;
char line[MAXLINE],enm[NAMELEN+1];
double esal=0.0;
if(!(fp1=fopen("emp.var","r")))
{
printf("\ncannot open the file \" emp.var\"\n");
exit(0);
}
if(!(fp2=fopen("emp.fix","w")))
{
printf("\ncannot open the file \" emp.fix\"\n");
exit(0);
}
while(fscanf(fp1,"%d %s %d %lf",&eno,enm,&eage,&esal)!=EOF)
{
pad(enm,NAMELEN);
sprintf(line,"%04d|%25.25s|%02d|%7.2f",eno,enm,eage,esal);
fprintf(fp2,"%s\n",line);
}
fclose(fp1);
}
Program for sorting records in a file, Using linked list and insertion sort, records are sorted.
Posted by admin in C Examples on June 27th, 2009
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
int eno;
char *rec;
struct node_st *next;
};
typedef struct node * NODE ;
NODE add(NODE list,int eno,char *rec);
void writetofile(NODE list,char *fn);
int main(int argc,char* argv[])
{
int nu;
char *buf,*temp;
NODE list=NULL;
FILE *fp;
if(argc !=2)
{
printf("Usage: sort <filename>");
exit(0);
}
buf=(char *)malloc(80);
temp=(char *)malloc(80);
if((fp=fopen(argv[1],"r"))==NULL)
{
printf("%s file open error",argv[1]);
exit(0);
}
while(fgets(buf,80,fp))
{
strcpy(temp,buf);
nu=atoi(strtok(buf,"|"));
list=add(list,nu,temp);
}
fclose(fp);
writefile(list,argv[1]);
free(buf);
free(temp);
}
void writetofile(NODE list,char *fn)
{
FILE *fp;
NODE p;
fp=fopen(fn,"w");
p=(NODE)(malloc(sizeof(struct node_st)));
p=list;
while(p!=NULL)
{
fprintf(fp,"%s",p->rec);
p=p->next;
}
}
NODE add(NODE list,int eno,char *rec)
{
NODE p,q,r=NULL;
p=(NODE)(malloc(sizeof(struct node_st)));
p->rec=(char *)malloc(strlen(rec)+1);
p->eno=eno;
strcpy(p->rec,rec);
if (list==NULL)
{
p->next=NULL;
list=p;
}
else
{
if((list->eno)>(p->eno))
{
p->next=list;
list=p;
}
else
{
for(q=list;q!=NULL&& (q->eno)<(p->eno);q=q->next)
r=q;
p->next=r->next;
r->next=p;
}
}
return list;
}
Program for changing records of one file with another.
Posted by admin in C Examples on June 27th, 2009
#include<stdio.h>
#include<stdlib.h>
void strparse(char *buf, char *[]);
int main(int argc,char *argv[])
{
FILE *fp1 = NULL,*fp2 = NULL;
int eno,eage, eno1,eage1,i=0,j=0,count=0;
char line[80],enm[26],enm1[26],buf[80],buf1[80],*str1[80]={0,} , *str2[80] = {0,},*tempb,*stri[25];
double esal=0.0,esal1=0.0;
if(argc!=2)
{
printf("Usage: transaction <file name>");
exit(0);
}
fp1=fopen(argv[1],"r");
fp2=fopen("emp.fix","r");
if(!fp1 || !fp2)
{
printf(" Error in file open \n");
exit(0);
}
while(fgets(buf,80,fp1))
{
stri[i]=(char *)malloc(80);
if (fgets(buf1,80,fp2))
{
strparse(buf,str1);
eno=atoi(str1[0]);
strcpy(enm,str1[1]);
eage=atoi(str1[2]);
esal=atof(str1[3]);
strparse(buf1,str2);
eno1=atoi(str2[0]);
strcpy(enm1,str2[1]);
eage1=atoi(str2[2]);
esal1=atof(str2[3]);
if(eno1==eno)
{
if(enm)
strcpy(enm1,enm);
if(eage!=0)
eage1=eage;
if(esal!=0)
esal1=esal;
}
sprintf(stri[i],"%04d|%s|%02d|%7.2f\n",eno1,enm1,eage1,esal1);
i++;
}
}
fclose(fp1);
fclose(fp2);
fp2=fopen("emp.fix","w");
for(j=0;j<i;j++)
fprintf(fp2,"%s",stri[j]);
}
void strparse(char *buf,char *str[])
{
int i=0,j=0;
char *tempb;
for(tempb=buf; *tempb!='\0'; tempb++)
{
if(!str[j])
str[j]=(char*)malloc(100);
if(*tempb!='|')
{
*(str[j]+i)=*tempb;
i++;
}
else
{
*(str[j]+i)='\0';
j++;
i=0;
}
}
}
PROGRAM TO DEMONSTRATE FILE HANDLING, USING STRUCTURE AND DYNAMICALLY ALLOCATION OF MEMORY.
Posted by admin in C Examples on May 15th, 2009
This program shows that how to use a Structure with File handling. File consists of information of students like their Name, Roll number, and Branch. We can also modify this information.
#include <stdio.h> //HEADER FILES
#include <string.h>
#include <ctype.h>
struct student //STRUCTURE DEFINITION
{
long int rollno;
char name[40],branch[10];
}stud1,stud2;
FILE *ptr1,*ptr2; //GLOBAL FILE POINTERS
int menu(void); //FUNCTION PROTOTYPES
int submenu(int);
void target(int,int,long int *,char []);
void copy(void);
void write(FILE *,struct student);
void found(struct student);
int getit(int,int *,long int,char[]);
void add(void);
void delete(void);
void modify(void);
void search(void);
void display(void);
main() //MAIN() STARTS
{
int i,j,k,choice;
do
{
choice=menu(); //CALLING menu()
switch(choice)
{
case 1 : add(); //CALLING add()
break;
case 2 : delete(); //CALLING delete()
break;
case 3 : modify(); //CALLING modify()
break;
case 4 : search(); //CALLING search()
break;
case 5 : display(); //CALLING display()
break;
case 6 : printf("\n\t PROGRAM OVER\n\n");
break;
}
}while(choice!=6);
}
int menu() //FUNCTION TO PRINT MAIN MENU AND RETURN THE CHOICE
{
char choice;
while(1)
{
printf("\n\n\n STUDENTS' RECORD FILE");
printf("\n MAIN MENU");
printf("\n ADD RECORD :: 1");
printf("\n DELETE RECORD :: 2");
printf("\n MODIFY RECORD :: 3");
printf("\n SEARCH RECORD :: 4");
printf("\n DISPLAY ALL RECORDS :: 5");
printf("\n EXIT :: 6");
printf("\n ENTER YOUR CHOICE :: ");
scanf("%c",&choice);
if((isdigit(choice))&&((choice>=49)&&(choice<=54)))
return(choice-48);
}
}
int submenu(int type) //FUNCTION TO PRINT SUBMENUS ACCORDING TO THE TYPE
{
char ask[][10]={"DELETE","MODIFY","SEARCH"};
int choice;
do
{
printf("\n\t\t %s MENU",ask[type-1]);
printf("\n\t %s BY ROLL NO. :: 1",ask[type-1]);
printf("\n\t %s BY NAME :: 2",ask[type-1]);
printf("\n\t RETURN TO MAIN MENU :: 3");
printf("\n\t ENTER YOUR CHOICE :: ");
scanf("%d",&choice);
}while((choice!=1)&&(choice!=2)&&(choice!=3));
return choice;
}
void target(int choice,int type,long int *roll,char name[]) //FUNCTION TO GET THE RECORD TO BE SEARCHED FOR
{
char ch,opt[][10]={"ROLL NO","NAME"};
char ask[][10]={"DELETED","MODIFIED","SEARCHED"};
int j;
printf("\n ENTER THE %s OF STUDENT WHOSE RECORD IS TO BE %s :: ",opt[choice-1],ask[type-1]);
if(choice==1)
scanf("%ld",roll);
else
{
ch=getchar();
j=0;
ch=getchar();
while(ch!='\n')
{
name[j++]=ch;
ch=getchar();
}
name[j]='\0';
}
}
void copy(void) //FUNCTION TO COPY FILE (*ptr1) TO FILE (*ptr2)
{
int j;
char ch;
fscanf(ptr1,"%ld",&stud1.rollno);
ch=getc(ptr1);
j=0;
do
{
stud1.name[j]=getc(ptr1);
}while(stud1.name[j++]!='\0');
ch=getc(ptr1);
fscanf(ptr1,"%s",stud1.branch);
fprintf(ptr2,"%ld\n",stud1.rollno);
fprintf(ptr2,"%s",stud1.name);
putc('\0',ptr2);
putc('\n',ptr2);
fprintf(ptr2,"%s",stud1.branch);
putc('\0',ptr2);
putc('\n',ptr2);
}
void write(FILE *p,struct student stud) //FUNCTION TO WRITE CONTENTS OF OBJECT stud IN FILE *p
{
fprintf(p,"%ld\n",stud.rollno);
fprintf(p,"%s",stud.name);
putc('\0',p);
putc('\n',p);
fprintf(p,"%s",stud.branch);
putc('\0',p);
putc('\n',p);
}
void found(struct student stud) //FUNCTION TO PRINT A RECORD IF IT IS IN THE FILE
{
printf("\n ROLL NO. :: %ld",stud.rollno);
printf("\n NAME :: %s",stud.name);
printf("\n BRANCH :: %s\n",stud.branch);
}
int getit(int choice,int *flag,long int roll,char nam[]) //FUNCTION TO READ ONE RECORD FROM FILE AND TO...
{ //...CHECK WHETHER IT IS THE TARGET RECORD...
int find=0,j; //...IT RETURNS 1 IF MATCH IS FOUND, 0 OTHERWISE
char ch;
fscanf(ptr1,"%ld",&stud1.rollno);
ch=getc(ptr1);
j=0;
do
{
stud1.name[j]=getc(ptr1);
}while(stud1.name[j++]!='\0');
ch=getc(ptr1);
fscanf(ptr1,"%s",stud1.branch);
if((choice==1)&&(stud1.rollno==roll))
find=1;
else if((choice==2)&&(!strcmp(stud1.name,nam)))
find=1;
if(find)
{
*flag=1;
printf("\n RECORD FOUND::");
found(stud1); //CALLING FUNCTION found()
ch=getchar();
}
return (find);
}
void add(void) //FUNCTION TO PERFORM ADD OPERATION IN FILE
{
int i,j,k,rec,num,no;
char cho,ch;
struct student *stud; //STRUCTURE POINTER FOR DYNAMIC MEMORY ALLOCATION
ptr1=fopen("records.txt","r"); //OPENING THE RECORD FILE
if(ptr1==NULL)
{
printf("CANNOT OPEN THE RECORD FILE");
exit();
}
fscanf(ptr1,"%d",&num); //READING THE NO. OF RECORDS IN FILE
ptr2=fopen("temp.txt","w"); //OPENING A TEMPORARY FILE
fprintf(ptr2,"%d\n",num);
for(i=0;i<num;i++)
copy();
no=0;
do
{
printf("\n ENTER TNE NO. OF RECORDS TO BE ADDED ::");
scanf("%d",&rec);
stud=(struct student *)(calloc(rec,sizeof(struct student))); //DYNAMIC ALLOCATION
for(k=0;k<rec;k++)
{
printf("\n\n ENTER ROLL NO. OF STUDENT %d :: ",k+1);
scanf("%ld",&stud[k].rollno);
ch=getchar();
printf("\n ENTER STUDENT'S NAME :: ");
j=0;
ch=getchar();
while(ch!='\n')
{
stud[k].name[j++]=ch;
ch=getchar();
}
stud[k].name[j]='\0';
printf("\n ENTER STUDENT'S BRANCH :: ");
scanf("%s",stud[k].branch);
}
ch=getchar();
printf("\n DO U WANT TO SAVE THESE %d RECORDS (Y/N)??",rec);
cho=getchar();
if((cho=='n')||(cho=='N'))
goto label;
no+=rec;
for(k=0;k<rec;k++)
write(ptr2,stud[k]);
printf("\n %d RECORD SUCCESSFULLY ADDED",rec);
label:
ch=getchar();
printf("\n WANT TO ENTER MORE RECORDS (Y/N) ::");
cho=getchar();
}while((cho=='y')||(cho=='Y'));
free(stud); //FREE THE ALLOCATED MEMORY
fclose(ptr1);
fclose(ptr2);
printf("\n TOTAL %d RECORD SUCCESSFULLY ADDED",no);
ptr1=fopen("temp.txt","r");
if(ptr1==NULL)
{
printf("CANNOT OPEN THE RECORD FILE");
exit();
}
fscanf(ptr1,"%d",&num);
ptr2=fopen("records.txt","w");
fprintf(ptr2,"%d\n",num+no);
for(i=0;i<num+no;i++) //COPY TEMP TO RECORDS
copy();
fclose(ptr1);
fclose(ptr2);
}
void delete(void) //FUNCTION TO PERFORM DELETE OPERATION
{
int i,j,flag,find,choice,num,rec;
long int roll;
char cho,ch,opt[][10]={"ROLL NO","NAME"},nam[40],dept[10];
do
{
ptr1=fopen("records.txt","r");
fscanf(ptr1,"%d",&num);
if(num==0)
{
printf("\n NO MORE RECORDS IN FILE!!!!!");
printf("\n RETURNING TO MAIN MENU");
break;
}
choice=submenu(1);
if(choice==3)
return;
target(choice,1,&roll,nam);
flag=rec=0;
ptr2=fopen("temp.txt","w");
fprintf(ptr2,"%d\n",num);
for(i=0;i<num;i++)
{
cho='n';
find=getit(choice,&flag,roll,nam);
if(find)
{
printf("\n DO U WANT TO DELETE THIS RECORD (Y/N)??");
cho=getchar();
}
if((cho=='y')||(cho=='Y'))
{
rec++;
continue;
}
write(ptr2,stud1);
}
fclose(ptr1);
fclose(ptr2);
ptr2=fopen("records.txt","w");
ptr1=fopen("temp.txt","r");
fscanf(ptr1,"%d",&num);
fprintf(ptr2,"%d\n",num-rec);
for(i=0;i<num-rec;i++)
copy();
fclose(ptr1);
fclose(ptr2);
if((!find)&&(!flag))
printf("\n RECORD NOT FOUND");
if(rec)
printf("\n %d RECORD SUCCESSFULLY DELETED",rec);
ch=getchar();
printf("\n WANT TO DELETE SOME OTHER RECORDS (Y/N) ::");
cho=getchar();
}while((cho=='y')||(cho=='Y'));
}
void modify(void) //FUNCTION TO MODIFY RECORDS
{
int i,j,flag,find,choice,num,rec;
long int roll;
char cho,ch,nam[40],dept[10];
do
{
ptr1=fopen("records.txt","r");
fscanf(ptr1,"%d",&num);
if(num==0)
{
printf("\n NO RECORDS IN FILE!!!!!");
printf("\n RETURNING TO MAIN MENU");
break;
}
choice=submenu(2);
if(choice==3)
return;
target(choice,2,&roll,nam);
flag=rec=0;
ptr2=fopen("temp.txt","w");
fprintf(ptr2,"%d\n",num);
for(i=0;i<num;i++)
{
cho='n';
find=getit(choice,&flag,roll,nam);
if(find)
{
printf("\n DO U WANT TO MODIFY THIS RECORD (Y/N)??");
cho=getchar();
}
if((cho=='y')||(cho=='Y'))
{
rec++;
printf("\n ENTER THE NEW ROLL NO. STUDENT :: ");
scanf("%ld",&stud2.rollno);
ch=getchar();
printf("\n ENTER STUDENT'S NAME :: ");
j=0;
ch=getchar();
while(ch!='\n')
{
stud2.name[j++]=ch;
ch=getchar();
}
stud2.name[j]='\0';
printf("\n ENTER STUDENT'S BRANCH :: ");
scanf("%s",stud2.branch);
write(ptr2,stud2);
continue;
}
write(ptr2,stud1);
}
fclose(ptr1);
fclose(ptr2);
ptr2=fopen("records.txt","w");
ptr1=fopen("temp.txt","r");
fscanf(ptr1,"%d",&num);
fprintf(ptr2,"%d\n",num);
for(i=0;i<num;i++)
copy();
fclose(ptr1);
fclose(ptr2);
if((!find)&&(!flag))
printf("\n RECORD NOT FOUND");
if(rec)
printf("\n %d RECORD SUCCESSFULLY MODIFIED",rec);
ch=getchar();
printf("\n WANT TO MODIFY SOME OTHER RECORDS (Y/N) ::");
cho=getchar();
}while((cho=='y')||(cho=='Y'));
}
void search(void) //FUNCTION TO SEARCH FOR A RECORD
{
int i,j,flag,find,choice,num,rec;
long int roll;
char cho,ch,nam[40],dept[10];
do
{
ptr1=fopen("records.txt","r");
fscanf(ptr1,"%d",&num);
if(num==0)
{
printf("\n NO RECORDS IN FILE!!!!!");
printf("\n RETURNING TO MAIN MENU");
break;
}
choice=submenu(3);
if(choice==3)
return;
target(choice,3,&roll,nam);
flag=rec=0;
for(i=0;i<num;i++)
{
cho='n';
find=getit(choice,&flag,roll,nam);
}
fclose(ptr1);
if((!find)&&(!flag))
printf("\n RECORD NOT FOUND");
if(rec)
printf("\n %d RECORDS FOUND",rec);
ch=getchar();
printf("\n WANT TO SEARCH SOME OTHER RECORDS (Y/N) ::");
cho=getchar();
}while((cho=='y')||(cho=='Y'));
}
void display(void) //FUNCTION TO DISPLAY ALL RECORDS
{
int i,j,num;
long int roll;
char ch,cho;
i=1;
ptr1=fopen("records.txt","r");
fscanf(ptr1,"%d",&num);
if(num==0)
{
printf("\n NO RECORDS IN FILE!!!!!");
printf("\n RETURNING TO MAIN MENU");
return;
}
for(i=0;i<num;i++)
{
fscanf(ptr1,"%ld",&stud1.rollno);
ch=getc(ptr1);
j=0;
do
{
stud1.name[j]=getc(ptr1);
}while(stud1.name[j++]!='\0');
ch=getc(ptr1);
fscanf(ptr1,"%s",stud1.branch);
printf("\n SR. NO. %d",i+1);
found(stud1);
if(!((i+1)%5))
{
cho=getchar();
printf("\n PRESS ENTER TO CONTINUE");
cho=getchar();
}
}
printf("\n TOTAL NO. OF RECORDS = %d",num);
fclose(ptr1);
}


Recent Comments