繁体   English   中英

用C将数据写入不同的文件

[英]Writing data in different files in C

我目前正在学习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 [])”是我写入文件的位。

我的第一个建议是:如果在main中不需要filename变量,则将其移至writeFile()。 较少的参数移动,使您的代码更整洁。

您的问题在writeFile()函数内部:

strcpy(filename, patient[i].name);

您从未初始化过i变量。 它可能总是被初始化为0,因此您总是要写入创建的第一个文件。 尝试将该行更改为此:

strcpy(filename, patient[noAgt-1].name);

而且您应该看到代码工作得更好。 我认为仍然不是最佳解决方案,因为noAgt在写入文件之前可能不应增加。 但这应该可以使您继续清理代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM