0

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

那是我的代码:

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

它显示分段错误=(

4

1 回答 1

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");.

于 2013-10-18T00:23:21.800 回答