Home > database >  unable to read data from txt file
unable to read data from txt file

Time:10-09

This is the first code to write user data into a file

#include<stdio.h>
#include<conio.h>
void main()
{
   FILE *fpr;
   char ch='y';
   struct student 
   {
       int reg;
       char name[50],remarks[10];
   };
   struct student a;
   fpr=fopen("recstruct.txt","wb");
   if(fpr==NULL)
   {
       printf("file does not exist");
   }
   while (ch=='y')
   {
       printf("enter the register number ,name and remarks:\n");
       scanf("%d",&a.reg);
       scanf("%s",&a.name);
       scanf("%s",&a.remarks);
       
       fwrite(&a,sizeof(a),1,fpr);
       printf("do you want to add more record (y/n):\n");
       ch=getche();
       printf("\n\n");
   }
   fclose(fpr);
   
  }

the input I gave was:

1
charana
pass
y

2
charana
pass

which runs correctly but the text file is being saved in the following format :

   charana                     Ð>*  ùjö       pass         charana                     
Ð>*  ùjö       pass      

the second program here is to read a user defined register number from the saved text file and then display the details of that particular register number such as name and remarks .

#include<stdio.h>
  void main()
    {
    struct studentdata
    {
        int reg;
        char name[50],remarks[50]; 
    }a;
     
    int reg,flag=0;
    char name;
    FILE * fpr;
    fpr=fopen("recstruct.txt","rb");
    if(fpr==NULL)
    {
        printf("file does not exist");
    }
    printf("enter the registration number:\n");
    scanf("%d",&reg);
    while(fread(&a,sizeof(a),1,fpr)>0 && flag==0)
    {
      if (a.reg==reg)
      {
          flag=1;
          printf("record found\n");
          printf("student name:%s registration number: %d\t  remarks:%s",a.name,a.reg,a.remarks);
      }

    }
    if (flag==0)
    {
        printf("record not found");
    }
    fclose(fpr);
    }

but the program returns "not found" for any input given by the user other than the first line data

enter the registration number:
2
record not found

I cannot figure out where the problem is ,whether the first program or the second ..please help me solve the same .

CodePudding user response:

Your structs used for reading and writing are different sizes:

struct student 
{
    int reg;
    char name[50],remarks[10];
};

vs.

struct studentdata
{
    int reg;
    char name[50],remarks[50]; 
}a;

Specifically, remarks is different size.

  • Related