I wrote a program that first writes the data into structure,which is then written to a file using fprint
function and then i again want that data to be displayed into the screen,for this purpose i used fscanf
function however something is wrong,i cannot do any of those.
#include<stdio.h>
#include<stdlib.h>
struct student
{
int rollNo,intakeYear;
char name[20];
};
int main()
{
struct student s[2];
FILE *ptr;
ptr = fopen("student.txt","w+");
if(ptr == NULL)
{
printf("Couldnot open the file");
exit(1);
}
for(int i = 0 ; i < 2 ; i++)
{
printf("Enter the name of student\n");
scanf("%s",s[i].name);
printf("Enter the roll number\n");
scanf("%d",&s[i].rollNo);
printf("Enter the intakeYear\n");
scanf("%d",&s[i].intakeYear);
fprintf(ptr,"%s%d%d",s[i].name,s[i].rollNo,s[i].intakeYear);
}
for(int i = 0 ; i < 2 ; i++)
{
fscanf(ptr,"%s%d%d",s[i].name,&s[i].rollNo,&s[i].intakeYear);
printf("Name:%s",s[i].name);
printf("Roll:%d\n",s[i].rollNo);
printf("Intake Year:%d\n",s[i].intakeYear);
}
fclose(ptr);
return 0;
}
I don't know whats wrong here,however if i remove the fscanf part of the code,the file gets created and data is written to it too.