Points to Note:
void rewind(FILE *stream) - Sets the file position to the beginning of the file of the given stream.
void fseek(FILE *stream, long int offset, int whence) - Sets the file position of the stream to the given offset.. ( More informally , it moves the file position to particular offset from the whence. )
whence is nothing but the starting point, it can take values SEEK_SET - Beginning of the file,
SEEK_CUR - Current position of the file, SEEK_END - End of the file
#include<stdio.h>
struct student{
int roll;
char name[100];
};
void main()
{
FILE *f;
struct student s[100];
f=fopen("student.txt","w+");
fprintf(f,"Roll NO:\tName:\n");
int n,i;
printf("Enter the no of students..");
scanf("%d",&n);
printf("\nEnter the roll no and the name of each student one by one..");
// Writing to a file...
for(i=0;i<n;i++){
scanf("%d",&s[i].roll);
scanf("%s",s[i].name);
fprintf(f,"%d\t%s\n",s[i].roll,s[i].name);
}
// Reading from a file...
rewind(f);
char t;
while(!feof(f)){
t=fgetc(f);
printf("%c",t);
}
// Modifying a file...
char no[50],newname[100];
printf("\nEnter the roll no of the student to be modified..");
scanf("%s",no);
printf("\nEnter the new name of the student..");
scanf("%s",newname);
rewind(f);
char temp[100];
while(!feof(f)){
fscanf(f,"%s",temp);
if(strcmp(temp,no)==0){
break;
}
}
fseek(f,1,SEEK_CUR);
fputs(newname,f);
// Reading a modified file...
printf("\nThe modified file is...\n");
rewind(f);
while(!feof(f)){
t=fgetc(f);
printf("%c",t);
}
fclose(f);
}
Corner Case :
Sorry for the inconvenience, this program allows you to modify the existing student name with a new student name only with same length.. I'll try handle this case in my future posts..
No comments:
Post a Comment