Class Discussion Programme
#include<conio.h>
#include<stdio.h>
#include<string.h>
FILE *nameptr;
//function declarations
void save();
void read ();
void data_entry();
void view();
//global variables
char name[5][50];
int amount[5];
int main()
{
data_entry();
view();
data_entry();
save();
read();
view();
getch();
return 0;
}
//this function will write to the file
void save()
{
//this is a check to see if the file can open
if((nameptr = fopen("NameFile.txt","w"))== NULL)
{
printf("File cannot open");
}
else
{
printf("\n\nFile is open"); //indication that the file has open
//writing to the file (using fprintf) from 2 arrays
for(int num = 0; num <=4; num++)
{
fprintf(nameptr,"%s\t%d\n",name[num],amount[num]);
}
//indication that thew writing took place
printf("\nData entered into file...GO CHECK IT OUT!!! COOL");
}
fclose(nameptr); //must close file after use. You must mention the pointer
}
void read()
{
//Read from the file (using fscanf) into 2 arrays
if((nameptr = fopen("NameFile.txt", "r"))== NULL)
{
printf("File cannot open");
}
else
{
printf("READING FROM FILE");
for(int c = 0; c <= 4; c++)
{
fscanf(nameptr, "%s\t%d\n", name[c],&amount[c]);
}
}
fclose(nameptr);
}
void data_entry()
{
for(int n=0; n<=4; n++)
{
printf("\n\nPlease enter name of fruit %d\t",n+1);
fflush(stdin);
gets(name[n]);
printf("\nPlease the amount of %s\t", name[n]);
fflush(stdin);
scanf("%d",&amount[n]);
}
}
void view()
{
for(int n = 0; n<=4; n++)
{
printf("The number of %s is %d\n",name[n], amount[n]);
}
}