从两个文本文件排序c

时间:2013-10-18 00:17:28

标签: c

我在data1.text上有两个已排序的序列,data2.txt中的另一个包含20个分拣编号。我需要创建代码sort.c,从两个txts读取数字,同时比较它们并在sort.txt中输出较小的数字,因此它是kinnda合并排序)

这是我的代码:

#include <stdio.h>
int main(int argc,char *argv1[],char *argv2[],char *argv3[])
    {

        char *f1 = argv1[1];// taking filename1 from args
        char *f2 = argv2[1];// taking filename2 from args
        char *f3 = argv3[1];// taking filename2 from args
        FILE *fp1,*fp2,*fp3;

        fp1 = fopen(f1,"r");
        fp2 = fopen(f2,"r");
        fp3 = fopen(f2,"w");// sort.txt file so 'w'
        int num1,num2;
        fscanf (fp1, "%d", &num1);
        fscanf (fp2, "%d", &num2);
        while (!feof(fp1) && !feof(fp2)) {
        if (num1<num2)
            {
                fprintf(fp3,"%d\t",num1);// print num 1
                fscanf (fp1, "%d", &num1);  // read num1
            }
            else{
                fprintf(fp3,"%d\t",num2);
                fscanf (fp2, "%d", &num2);  // read num2
            }
        }

         if (!feof(fp1))
         {
            while (!feof(fp1))
            {
                fprintf(fp3,"%d\t",num1);// print num 1
                fscanf (fp1, "%d", &num1);  // read num1
            }
         }
            else
            {

                while (!feof(fp2))
                {
                    fprintf(fp3,"%d\t",num2);
                    fscanf (fp2, "%d", &num2);  // read num2
                }
            }


        fclose(fp1);// closing file f1
        fclose(fp2);// closing file f2
        fclose(fp3);// closing file f2

        return 0;
}

显示分段错误=(

1 个答案:

答案 0 :(得分:3)

您的main错了。应该是int main(int argc, char **argv)。 然后而不是

    char *f1 = argv1[1];// taking filename1 from args
    char *f2 = argv2[1];// taking filename2 from args
    char *f3 = argv3[1];// taking filename2 from args

类似

    char *f1 = argv[1];// taking filename1 from args
    char *f2 = argv[2];// taking filename2 from args
    char *f3 = argv[3];// taking filename2 from args

但在这些行之前,您应该检查argc是否有正确的参数数量。 您可能需要fp3 = fopen(f3,"w");而不是fp3 = fopen(f2,"w");