C语言初学者求助!关于从键盘读入姓名和电话号码,将它们写入一个文件的问题。
程序运行后,找不到文件。不知道哪里出错。代码也不知道怎么改!这样写代码有什么问题?要怎么解决?具体代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#define NAME_LEN 21
#define TEL_LEN 11
typedef struct Record Record;
struct Record
{
char name[NAME_LEN];
char Tel[TEL_LEN];
Record *next;
};
Record *get_person(Record *pcurrent);
void get_name(char *pname, size_t size);
void write_file(Record *first, char *filename, FILE *pfile);
void free_record(Record *first);
int main(void)
{
Record *first = NULL;
Record *current = NULL;
Record *previous = NULL;
char more = '\0';
printf("这是一个从键盘读入姓名和电话号码,将它们写入一个文件的程序!\n");
while(true)
{
printf("现在请确认是否有从键盘读入姓名和电话号码:Y:是!N:否! ");
scanf(" %c", &more);
fflush(stdin);
if(toupper(more) == 'N')
break;
if(first == NULL)
first = current;
if(previous != NULL)
previous -> next = current;
get_person(current);
previous = current;
}
FILE *pfile = NULL;
char *filename = "myTel.txt";
write_file(first, filename, pfile);
free_record(first);
return 0;
}
Record *get_person(Record *pcurrent)
{
pcurrent = (Record*)malloc(sizeof(Record));
if(!pcurrent)
{
printf("没有分配内存!\a\a\a\n");
exit(1);
}
printf("现在从键盘读入不超过 %d 字节姓名: ", NAME_LEN - 1);
get_name(pcurrent -> name, NAME_LEN);
printf("现在从键盘读入%s的电话号码: ", pcurrent -> name);
get_name(pcurrent -> Tel, TEL_LEN);
pcurrent -> next = NULL;
return pcurrent;
}
void get_name(char *pname, size_t size)
{
fflush(stdin);
fgets(pname, size, stdin);
size_t len = strlen(pname);
if(pname[len - 1] == '\n')
pname[len - 1] = '\0';
}
void write_file(Record *first, char *filename, FILE *pfile)
{
Record *pcurrent = NULL;
for(pcurrent = first; pcurrent != NULL; pcurrent = pcurrent -> next)
{
if(!(pfile = fopen(filename, "a")))
{
fprintf(stderr, "打开%s文件不成功!\a\a\a\n", filename);
exit(1);
}
setvbuf(pfile, NULL, _IOFBF, BUFSIZ);
size_t len_name = strlen(pcurrent -> name);
if(EOF == fputs(pcurrent -> name, pfile))
{
fprintf(stderr, "%s写入%s文件不成功!\a\a\a\n", pcurrent -> name, filename);
exit(1);
}
int i = 0;
for(i = 0; i < NAME_LEN - len_name; ++i)
{
char ch1 = ' ';
if(EOF == fputc(ch1, pfile))
{
fprintf(stderr, "写入%s文件不成功!\a\a\a\n", filename);
exit(1);
}
}
if(EOF == fputs(pcurrent -> Tel, pfile))
{
fprintf(stderr, "电话号码写入%s文件不成功!\a\a\a\n", filename);
exit(1);
}
char ch2 = '\n';
if(EOF == fputc(ch2, pfile))
{
fprintf(stderr, "写入%s文件不成功!\a\a\a\n", filename);
exit(1);
}
fclose(pfile);
pfile = NULL;
}
}
void free_record(Record *first)
{
Record *pcurrent = NULL;
Record *previous = NULL;
pcurrent = first;
while(pcurrent != NULL)
{
previous = pcurrent;
pcurrent = pcurrent -> next;
free(previous);
previous = NULL;
}
free(first);
first = NULL;
}