2017-12-13 4 views
0

나는 지금 C를 공부하고 있는데 아직 좋지 않다. 나는 사람들의 이름을 입력하고 동시에 .txt 파일을 만들려는 프로그램을 작성하려고합니다. 예를 들어 "Richard"라고 입력하면 Richard.txt 파일이 생성됩니다. 그리고 .txt 파일 안에 다시 이름을 적고 싶습니다.C에서 다른 파일에 데이터 쓰기

첫 번째 이름을 입력하고 첫 번째 .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 (구조체 인사 환자 [], INT noAgt)"나는()의 WriteFile에가는 사람의 이름을 입력 비트입니다.

"void writeFile (struct personnel patient patient [], int noAgt, char filename [])"파일을 쓰는 곳의 비트입니다.

답변

0

첫 번째 조언은 다음과 같습니다. 파일 이름이이고 주 변수가 변수 인 경우 writeFile()으로 이동하십시오. 매개 변수가 덜 이동하고 코드를보다 깨끗하게 만듭니다.

귀하의 문제는의 WriteFile() 함수 내부 :

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

당신은 당신의 내가 변수를 초기화하지 않습니다. 항상 0으로 초기화 될 가능성이 높으므로 작성한 첫 번째 파일에 항상 기록합니다. 이 행을 다음으로 변경해보십시오.

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

코드가 더 잘 작동해야합니다. 아직 내 의견에 가장 좋은 해결책이 아니기 때문에 noAgt은 파일을 작성하기 전에 증가하지 않아야합니다. 하지만 코드를 정리할 수 있습니다.