我需要你的帮助来指出我在阅读文件和写入另一个文件时遇到了什么问题。问题是我的输出文件中没有任何内容可以写入结果。目前正在修改我的程序Can't deallocate memory in my C program。现在我应该使用命令行参数进行读写,但到目前为止还没有成功。我想我的功能有误,但不知道如何修复它。这是我的struct def和main()函数
typedef struct{
char name[25];
char street[25];
char citystate[25];
char zip[6];
}student;
typedef student *studinfo;
int main(int argc, char *argv[])
{
FILE *fp1, *fp2; /* file pointer */
/* see if correct number of command line arguments */
if (argc != 3) {
printf("Something wrong with arguments\n");
exit(1);
}
/* open file for input */
if ((fp1 = fopen(argv[1], "r")) == NULL) {
printf("Cannot open file to read \n");
exit(1);
}
fp2 = fopen(argv[2], "w");
int count = 0;
student *studptr[49];
getinfo(studptr, &count, fp1);/*call getinfo function to get student info*/
sortit(studptr, count); /*call sortit function to sort info based on zip code*/
result(studptr, &count, fp2); /*call result function to display sorted result*/
fclose(fp1);
fclose(fp2);
return 0;
}
和我应该从文件中读取信息的函数以及我怀疑我的错误的位置
void getinfo(student *details[], int *count, FILE *fp1)
{
studinfo info;
/*Get student information*/
while (fp1 != NULL) {
info = (studinfo)malloc(sizeof(student));
fgets(info->name, 40,fp1);
fgets(info->street, 40,fp1);
fgets(info->citystate,40,fp1);
fgets(info->zip, 40, fp1);
details[(*count)++] = info; /*Increase pointer to next position*/
} /* End of while loop*/
} /* End of getinfo */
我有一个基于邮政编码排序信息的功能,以及将排序结果写入新文件的下一个功能,如下所示
void result(student *details[], int *count, FILE *fp2)
{
int i;
for (i = 0; i<(*count); i++) {
fprintf(fp2,"%s\n%s\n%s\n%s\n", details[i]->name, details[i]->street, details[i]->citystate, details[i]->zip); /* print info*/
fprintf(fp2, "*******************************\n");
}
} /* End of result*
答案 0 :(得分:0)
int get_line(FILE *fp, char *buffer, size_t buflen)
{
char line[4096];
assert(buflen > 1);
if (fgets(line, sizeof(line), fp) == 0)
return EOF;
size_t len = strlen(line);
if (line[len-1] == '\n')
line[--len] = '\0';
if (len >= buflen)
len = buflen - 1;
memmove(buffer, line, len);
buffer[len] = '\0';
return len;
}
void getinfo(student *details[], int *count, FILE *fp)
{
student *info;
while ((info = malloc(sizeof(*info)) != 0)
{
if (get_line(fp, info->name, sizeof(info->name)) == EOF ||
get_line(fp, info->street, sizeof(info->stree)) == EOF ||
get_line(fp, info->citystate, sizeof(info->citystate)) == EOF ||
get_line(fp, info->zip, sizeof(info->zip)) == EOF)
{
free(info);
return;
}
details[(*count)++] = info;
}
}
答案 1 :(得分:0)
while (fp1 != NULL) {
:无限循环。 - BLUEPIXY
这确实是主要问题。
我试过
while (fgetc(fp1) != EOF) {
:没有用
这样做不正确,因为fgetc()
会消耗后来遗失的角色。
您可以使用以下内容,并在名称之前放弃空格:
while (fscanf(fp1, "%*[ ]") != EOF)
{
…