Docsity

C Program to Read and Write Structured Data in a File, Exercises of Network Programming

Toggle sidebar
bg1
# include <conio.h>
# include <stdio.h>
# include <ctype.h>
# include <string.h>
# include <alloc.h>
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;i<count;i++)
{
printf("\n\t\t\t\tFriend #: %d\n",i+1);
printf("Enter name of the friend\n");
scanf("%s",(friend1+i)->name);
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
}
docsity.com
pf2

Partial preview of the text

Download C Program to Read and Write Structured Data in a File and more Exercises Network Programming in PDF only on Docsity!

include

include

include

include

include

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 }

docsity.com

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(); }

docsity.com