I'm studying C at the moment and I'm not that good yet. I am trying to write a program where I want to enter some people's name and create at the same time a .txt file with their name. For example if I type "Richard" it will create the file Richard.txt. And inside the .txt file I want to write again their name.
The only problem is that after I type the first name and create the first .txt file, entering a new name will not create a new .txt file. But instead it will put the second name in the first .txt file after the first name.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
struct personnel
{
char name[40];
};
int addPatient(struct personnel patient[], int noAgt);
void writeFile(struct personnel patient[], int noAgt, char filename[]);
void emptyBuffer(void);
int main()
{
struct personnel patient[50];
int ch = 'X';
int noAgt = 0;
char filename[100];
while (ch != 'q')
{
printf("\na)\tEnter new patient"
"\nb)\tWrite file"
"\nc)\tExit program"
"\n\nSelect: ");
ch = getche();
printf("\n\n");
switch (ch)
{
case 'a' :
noAgt = addPatient(patient, noAgt);
break;
case 'b' :
writeFile(patient, noAgt, filename);
break;
case 'c' :
exit(0);
}
}
}
int addPatient(struct personnel patient[], int noAgt)
{
printf("\nPatient %d.\nEnter name: ", noAgt + 1);
scanf("%39[^\n]", patient[noAgt].name);
while(getchar() != '\n')
{
;
}
return ++noAgt;
}
void writeFile(struct personnel patient[], int noAgt, char filename[])
{
int i;
FILE *fptr;
struct personnel rec;
strcpy(filename, patient[i].name);
emptyBuffer();
strcat(filename, ".aow.txt");
fptr = fopen(filename, "w");
for(i = 0; i < noAgt; i++)
{
rec = patient[i];
fprintf(fptr, "Name: %s ", rec.name);
}
fclose(fptr);
printf("\nFile of %d patients written.\n", noAgt);
}
void emptyBuffer(void) /* Empty keyboard buffer */
{
while(getchar() != '\n')
{
;
}
}
"int addPatient(struct personnel patient[], int noAgt)" Is the bit where I enter the name of the person that goes in writeFile().
"void writeFile(struct personnel patient[], int noAgt, char filename[])" Is the bit where I write the file.