0

I wrote a program that first writes the data into structure,which is then written to a file using fprintfunction 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.

IcanCode
  • 509
  • 3
  • 16
  • Tip: Don't have instances of hard-coded numbers like `2` littered through your code. Use a `#define` or a variable instead, `const` if you can, so there's one point of control here. – tadman Jan 25 '21 at 18:11
  • You will need to reset the file position to the beginning of the file to be able to read the data you wrote. See [`fseek`](http://www.cplusplus.com/reference/cstdio/fseek/). – fredrik Jan 25 '21 at 18:12
  • Don't forget than fprintf/fscsanf etc have return codes that you can check for errors. – Paul Hankin Jan 25 '21 at 18:15
  • Oh I should have used the `rewind` function – IcanCode Jan 25 '21 at 18:15
  • You should probably use fseek (https://stackoverflow.com/questions/11839025/fseek-vs-rewind#:~:text=2%20Answers&text=They%20are%20basically%20two%20different,choice%2C%20you%20should%20use%20fseek%20.) – fredrik Jan 25 '21 at 18:16

1 Answers1

0

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.

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28