gpt4 book ai didi

c - C中文件与文件之间读写的问题

转载 作者:行者123 更新时间:2023-11-30 17:23:58 24 4
gpt4 key购买 nike

我需要您的帮助来指出我在读取文件和写入另一个文件时做错了什么。问题是我在输出文件中没有得到任何应该写入结果的内容。目前正在修改我的程序Can't deallocate memory in my C program 。现在我应该使用命令行参数来读取和写入,但到目前为止还没有成功。我认为我的函数有错误,但不知道如何修复它。这是我的 struct def 和 main() func

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*

最佳答案

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;
}
}

关于c - C中文件与文件之间读写的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27352730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com