Hello I\'m programming in C language. my question is: I\'m new to programming in
ID: 3663121 • Letter: H
Question
Hello I'm programming in C language. my question is: I'm new to programming in C. I've been writing different structure problems to get better. But i am having trouble reading and writing to a file using a structure. I made up a text file and i would to create a structure using id, name, and age. I want to see the easiest way to read the file using a structure and then run the program displaying the ID with their name and birthday. Thank you for your help I really hope this helps me understand what i'm doing wrong overall. Thanks, if you could include any comments that would be greatly appreciated, thanks. Also any references to great source examples on the net would be awesome .
The text file i created is below but if you dont like it you could use something else. Thanks!
100 jesse 25
101 james 22
102 corey 33
103 angie 22
104 kayla 24
Explanation / Answer
Hopw this Example get YOu out of your problem comment if u need any help
#include<stdio.h>
#include<conio.h>
#include<process.h>
void read();
void write();
struct record
{
char name[30];
int id;
float sal;
}s;
main()
{
int ch;
clrscr();
while(1)
{
printf(" 1:Write Records");
printf(" 2:Read Records");
printf(" 3:Exit");
printf(" Enter Your Choice:- ");
scanf("%d",&ch);
switch(ch)
{
case 1:
write();
break;
case 2:
read();
break;
case 3:
exit(1);
default:
printf(" Option not Available ");
break;
}
}
getch();
}
void write()
{
int i,n=0;
FILE *fp;
fp=fopen("stu.dat","wb");
if(fp==NULL)
{
printf("can't create file");
getch();
exit(1);
}
printf(" How Many Records You Want to Enter:=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" Enter Employee ID := ");
scanf("%d",&s.id);
printf(" Enter Employee Name := ");
scanf("%s",s.name);
flushall();
printf(" Enter the Salary:=");
scanf("%f",&s.sal);
printf(" ***************** ");
fwrite(&s,sizeof(s),1,fp);
}
fclose(fp);
}
void read()
{
FILE *fp;
fp=fopen("stu.dat","rb");
if(fp==NULL)
{
printf("can't read file");
getch();
exit(1);
}
while(fread(&s,sizeof(s),1,fp)==1)
{
printf(" Employee ID := %d",s.id);
printf(" Employee Name := %s",s.name);
flushall();
printf(" Salary:= %f",s.sal);
printf(" ******************** ");
}
fclose(fp);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.