**Program which replaces a particular character in the file with another character. In case the character repeats then only the last occurrence is replaced.**
#include<stdio.h>
#include<conio.h>
int
main()
{
FILE *fp;
int pos; //Opening the file in the write mode.
fp=fopen("srecord.txt","w");
if(fp==NULL)
printf("\nError");
char str[]="Sample String in a
File";
char c,c1,c2; //Writing to the file using fputs
fputs(str,fp);
fflush(fp);
printf("\nEnter character you want to
search");
scanf("%c",&c1);
printf("\nEnter character you want to
modify");
fflush(stdin);
scanf("%c",&c2); //Taking the file pointer to the beginning
of the file
rewind(fp); //Reading the file character by character
till the EOF.
while((fscanf(fp,"%c",&c))!=EOF)
{
//Store the position with the match
if(c==c1)
pos=ftell(fp)-1;
}
//Take the file pointer to the beginning.
rewind(fp); //Position the file pointer at the
replacement point
fseek(fp,pos,0); //Printing other character at its place
fprintf(fp,"%c",c2); //Taking the pointer to the beginning
rewind(fp);
printf("\nContents of the file are
"); //Printing the contents on the screen
while((fscanf(fp,"%s",str))!=EOF)
printf("%s ",str);
fclose(fp); //Closing the file.
getch();
}
Program 2: Reading and writing data in to the file using structure.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> //Creating
structure
struct
student
{
char
name[20];
int
rollno;
float
marks;
};
void
Write();
void
Read();
FILE
*fp; //File stream pointer
int
count;
//Structure
Variable which will be read and written
struct
student s1;
int
main()
{
int
ch;
while(1)
{
printf("\n1.Write
Data");
printf("\n2.Read
Data");
printf("\n3.Exit");
printf("\nChoice");
scanf("%d",&ch);
if(ch==1)
{
Write();
}
if(ch==2)
{
Read();
}
if(ch==3)
exit(0);
}
}
void
Write()
{
count++;
//Open
the file in a+ mode so as to read and write data to the file
fp=fopen("K1201.txt","a+");
printf("\nName:-
");
fflush(stdin);
gets(s1.name);
printf("\nRoll
Number:- ");
scanf("%d",&s1.rollno);
printf("\nMarks:-
");
scanf("%f",&s1.marks);
//Use
the fwrite function to write the data to the file
fwrite(&s1,sizeof(struct
student),1,fp);
//Close
the file after writing the data
fclose(fp);
}
void
Read()
{
int
i;
//Open
the file in a+ mode so that we can read and write the data
fp=fopen("K1201.txt","a+");
for(i=0;i<count;i++)
{
//Read
all the records from the file one by one. We are reading an entire
//structure
variable one at a time
fread(&s1,sizeof(struct
student),1,fp);
printf("\nName:-
%s",s1.name);
printf("\nRoll
Number:- %d",s1.rollno);
printf("\nMarks:-
%f",s1.marks);
}
//Closing
the file
fclose(fp);
}
From site : http://ctechrockz.blogspot.com/
No comments:
Post a Comment