【问题标题】:Writing data in different files in C用C在不同文件中写入数据
【发布时间】: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[])" 是我写文件的位。

【问题讨论】:

    标签: c file loops


    【解决方案1】:

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

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

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

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

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

    您应该会看到代码运行得更好。在我看来仍然不是最好的解决方案,因为 noAgt 在写入文件之前可能不应该增加。但它应该让你继续清理你的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多