简体   繁体   中英

Writing and Reading to a file in C

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.

You are opening the file and writing to it, moving to the end of the file and then attempting to read it. You can use fseek or rewind functions and it may be a good idea to do so in some cases but in this case I would close the file after writing to it and reopen it for reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM