Google

Thursday, April 1, 2010

Lab Exercise 2: April 1, 2010

Rewrite the previous exercise to store the record inside a file called
data.txt. One line one record.

Also write a function to read from the file and print out the contents.

SOLUTION:
#include "stdio.h"
#include "string.h"

typedef struct name {
char firstname[16];
char lastname[16];
}NAME;

typedef struct student{
char id;
NAME studentname;
}STUDENT;

void main(){
FILE *f;
f = fopen("C:\\data.txt","w");
STUDENT csc202[2];

//--input---
for(int i=0; i<2; i++){
puts("enter id: ");
scanf("%c",&csc202[i].id);
fflush(stdin);
puts("enter firstname: ");
scanf("%s",csc202[i].studentname.firstname);
fflush(stdin);
puts("enter lastname: ");
scanf("%s",csc202[i].studentname.lastname);
fflush(stdin);
fprintf(f,"%c %s %s\n",
csc202[i].id, csc202[i].studentname.firstname,
csc202[i].studentname.lastname);
}
fclose(f);

//---output---
char myid; char firstname[16]={0},lastname[16]={0};
f = fopen("C:\\data.txt","r");
for(int i=0; i<2; i++){
fscanf(f,"%c%s%s",&myid,firstname,lastname);
printf("id: %c\nfirstname: %s\nlastname: %s\n",
myid,firstname,lastname);
}
fclose(f);

}