gpt4 book ai didi

c - C 中文本文件的合并和排序

转载 作者:行者123 更新时间:2023-11-30 18:59:31 25 4
gpt4 key购买 nike

我假设编写一个函数,逐行读取两个文本文件,比较它们,删除重复项,然后按字母顺序将它们放入第三个文件中......我已经为此工作了一个多月了,我仍然卡住了我尝试了几种方法来做到这一点,但一无所获...我被告知我必须使用 strcmp 来做到这一点,并且我不能使用任何其他预定义的排序函数...我也环顾四周网站,找不到太多对此有帮助的...任何帮助将不胜感激..这是我到目前为止所拥有的:

#include<stdio.h>
#include<string.h>


main (void)
{
char str [200];
char str2 [200];
char new [100];
char temp [100];
int row = 10;
FILE *fa = fopen ("book1.dat", "r");
FILE *fb = fopen ("book2.dat", "r");
FILE *fc = fopen ("fixed.txt", "w");

int i;
int j;
int k;

while (fgets (str, 200, fa) !=NULL && fgets (str2, 200, fb) !=NULL)
{
puts(str);
puts(str2);

if (strcmp( str, str2) ==0 )
{
strcpy (str , new);
} else {
strcpy (new, str);
strcpy (new, str2);
}
}
for ( i = 0; i < row; i++)
{
for (j = i+1; j< row; j++)
{
if(strcmp(new[i], new [j]) > 0)
{
strcpy (temp, new);
strcpy(new, new);
strcpy(new, temp);
}
}
}
for (i = 0; i < length; i ++)
{
fputs(new, fc);
}
}

最佳答案

您对 strcpy() 的使用很特殊。回想一下它的签名:

char *strcpy(char *dest, const char *src)

以下用法对我来说没有立即意义:

strcpy (new, str); // new now has str
strcpy (new, str2); // new now has str2

你已经有效地覆盖了那里的一些东西。我将从那里开始,看看还有什么可能无法按您的预期工作。此外,如果您可以使用 gcc,请考虑使用 gdb 来调试代码。 (您需要使用 -g 标志进行编译。)

关于c - C 中文本文件的合并和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10523927/

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