簡體   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