【发布时间】:2017-12-13 00:16:52
【问题描述】:
我现在正在学习 C,但我还没有那么好。我正在尝试编写一个程序,我想在其中输入一些人的名字并同时创建一个带有他们名字的 .txt 文件。例如,如果我键入“Richard”,它将创建文件 Richard.txt。在 .txt 文件中,我想再次写下他们的名字。
唯一的问题是,在我输入名字并创建第一个 .txt 文件后,输入新名称不会创建新的 .txt 文件。但它会将第二个名称放在第一个 .txt 文件中的第一个名称之后。
#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 person patient[], int noAgt)" 是我在 writeFile() 中输入人员姓名的位置。
"void writeFile(struct person patient[], int noAgt, char filename[])" 是我写文件的位。
【问题讨论】: