我是文件处理新手,需要一些帮助来读取包含人员记录的文本文件,其中包含姓名、地址、城市、州、邮政编码和电话号码,所有信息均以“\t”分隔,并且将其复制到另一个文件中。读取的文件可以保存任意数量的记录。
我希望能够仅按城市字母顺序对这些记录进行排序。我对文件处理很陌生,所以我不确定在读取文件后如何进行此操作以及如何在我的比较函数中进行此操作。另外,在我的代码中,我注释掉了一些代码,用于显示每个文件包含的内容。我的问题是,当它没有被注释掉并且是程序的一部分时,文本文件不会复制到目标文件。这是为什么?
感谢您提前提供的帮助!我的代码在这里:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct contacts {
char fname[1000];
char lname[1000];
char address[1000];
char city[1000];
char state[1000];
char zip[1000];
char num[1000];
}ContactType;
#define MaxContacts 1000
ContactType contacts[MaxContacts];
int ncontacts = 0;// update to number of records stored in contacts[]
int CompareCity(void *pa, void *pb);
int main()
{
char ch, copy, show, source_file[1000], target_file[1000];
FILE *source, *target;
printf("Enter name of file to copy\n");
gets(source_file);
source = fopen(source_file, "r");
if (source == NULL)
{
printf("Could not open file.\n");
exit(EXIT_FAILURE);
}
printf("Enter name of target file\n");
gets(target_file);
target = fopen(target_file, "w");
if (target == NULL)
{
fclose(source);
printf("Could not open file\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", source_file);
/*while ((ch = fgetc(source)) != EOF)
printf("%c", ch);
printf("\n");*/
qsort(contacts, ncontacts, sizeof contacts[0], CompareCity);
while ((copy = fgetc(source)) != EOF)
fputc(copy, target);
printf("File copied successfully.\n");
printf("The contents of %s file are :\n", target_file);
/*while ((show = fgetc(target)) != EOF)
printf("%c", show);
printf("\n");*/
fclose(source);
fclose(target);
return 0;
}
int CompareCity(void *pa, void *pb) {
return strcmp(((ContactType*)pa)->city, ((ContactType*)pb)->city);
}
最佳答案
回答有关注释代码的问题:
每个打开的文件都有一个文件指针
的概念,它指示发生读/写操作的当前位置。
第一个注释代码:
while ((ch = fgetc(source)) != EOF)
printf("%c", ch);
printf("\n");
输入文件中的所有字符后,文件指针位于文件末尾。
上面的代码尝试读取该文件。但是,文件指针已经位于文件末尾。
建议在读取/解析/排序文件之前使用rewind()
(或更好)lseek()
将文件指针移回到文件的开头。
第二个注释代码:
while ((show = fgetc(target)) != EOF)
printf("%c", show);
printf("\n");
也有类似的问题,文件指针已经位于新文件的末尾。
顺便说一句:fgetc()
返回一个“int”,而 EOF 是一个 int,因此 ch
的声明和 show
的声明必须是“int”而不是“char”。并且 EOF 无法正确与“char”进行比较。不需要对代码进行其他更改来处理“int”而不是“char”的声明。
关于C程序: Sort a text file with records alphabetical order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33326621/