

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This c program demonstrates how to read and write structured data in a file using the 'fscanf' and 'fprintf' functions. The program allows the user to enter the number of entries, name, and age of each friend to be stored in the file. It also provides functionality to display and extract data from the file.
Typology: Exercises
1 / 2
This page cannot be seen from the preview
Don't miss anything!


struct friends { char name[80]; int age; } friend1,friend2;
void main (void) {
FILE *ptr; int count, i; clrscr(); ptr =fopen("abc1.txt","w"); if (NULL == ptr) printf("Error: File not opened"); else { printf("File openend sucessfully\n\n\t-> Enter the number of entries you want to make in the file\n "); scanf("%d",&count); friend1 = (struct friends *)malloc(count); for (i=0;iname); printf("Enter age of the friend\n"); scanf("%d",&(friend1+i)->age); fprintf(ptr,"%s\t%d\n",(friend1+i)->name,(friend1+i)- >age);
}
free(friend1); // used to free memory, for the next entry i.e. we are over writing }
fclose(ptr); ptr=fopen("abc1.txt","r");
if (NULL!=ptr) { printf("\nFile read sucessfully\nThe Data in file:\n\n"); do { putchar(getc(ptr)); // getc gets data from ptr..and putchar prints it on the screen }
while(!feof(ptr)); // till end of file }
fclose(ptr);
ptr = fopen("abc1.txt","r");
if (NULL == ptr) printf("\n\nError: File not opened"); else { printf("\n\nExtracting Data from the file into structure:\n\n");
for (i=0;iname,&(friend2+i)- >age); // scans data from the saved file printf("\n\t\t\t\tFriend #: %d\n",i+1); printf("\nName of the friend:\t"); puts((friend2+i)->name); printf("\nAge of the friend:\t%d", (friend2+i)->age); } free(friend2); } fclose(ptr); getch(); }