THIS IS THE CODE USED TO EXPLAIN:
- HOW TO USE APPEND MODE, WHEN STORING TO FILE
- HOW TO STORE THE TO A FILE, THE NUMBER OF RECORDS STORED.
_________________________________________________________________
#include<conio.h>
#include<stdio.h>
#include<string.h>
char name[100][50], address[100][75];
int count;
FILE *countptr; //pointer to the file that holds the next available position
FILE *dataptr; //pointer to the file that hold the records
void fill(); // fill the arrays with data
void retrievecount(); //stores the next available position in count
void view (); //allow the user to view what is in the file
int main()
{
fill();
view();
getch();
return 0;
}
void retrievecount()
{
//open the file to read the integer value in the file and store it in count.
if((countptr = fopen("CountFile.txt","r")) == NULL)
{
printf("File cannot open");
}
else
{
fscanf(countptr, "%d", &count);
}
fclose(countptr);
}
void fill()
{
char choice;
retrievecount(); //putting a value in count
do
{
printf("\nEnter name:\t" );
fflush(stdin);
gets(name[count]);
printf("\nEnter address:\t" );
fflush(stdin);
gets(address[count]);
//each time a record is entered, it stored to the file in append mode
if((dataptr = fopen("DataFile.txt", "a"))== NULL)
{
printf("FILE CANNOT OPEN");
}
else
{
fprintf(dataptr, "%s\n%s\n", name[count], address[count]);
}
fclose(dataptr);
count++;
printf("\nWould you like to continue:\t" );
scanf("%c", &choice);
}while((count <100) && ((choice == 'Y') || (choice == 'y')));
//save updated count to file
if((countptr = fopen("CountFile.txt","w")) == NULL)
{
printf("File cannot open");
}
else
{
fprintf(countptr, "%d", count);
}
fclose(countptr);
}
void view()
{
retrievecount();
if((dataptr = fopen("DataFile.txt","r")) == NULL)
{
printf("File cannot open");
}
else
{
//allow count to determine how many times you loop.
for (int c=0; c < count; c++)
{
fgets(name[c],50,dataptr);
fgets(address[c],75,dataptr);
printf("Name is %sAddress is %s\n\n", name[c],address[c]);
}
}
fclose(dataptr);
}