C程序从文本文件中读取并将已排序的列表写入同一文本文件。我可以做哪些修改?

时间:2017-06-05 05:41:13

标签: c

以下程序在编译时出现以下错误:

  

./ vpl_test:第2行:18699分段错误(核心转储)./ solution

以下C程序可能出现什么问题?

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

void sort(long *sorted, int count,long value){
    int i=0;
    sorted[count] = value;
    if(count == 0)return;
    for(i=count;i>=0;i--){
        if(value<sorted[i-1])
        sorted[i] = sorted[i-1];
        else break;
    }
    sorted[i]=value;
}

int main(int argc,char *argv[]){
    FILE *fp = NULL;
    long sorted[1024];
    long value;
    int count = 0;
    int i=0;
    fp = fopen("brandlist.txt","r+");
    //fp = fopen("brandlist.txt","w");
    if(NULL == fp){
        perror("fopen");
        exit(0);
    }
    while(!feof(fp)){
        fscanf(fp,"%ld\n",&sorted[i]);
        sort(sorted,count,value);
        ++count;
    }
    for(i=0;i<count;i++){
        fprintf(fp,"%ld\n",sorted[i]);
    }

    if(fp){
        fclose(fp);
        fp = NULL;
    }
}

1 个答案:

答案 0 :(得分:0)

我无法重现段错误(可能是因为“幸运”或可能是因为输入错误)。
我所遇到的问题是排序输出中的排序错误和奇怪的值,我相信同样的问题会导致所有错误行为,包括你的情况下的段错误。

以下是您的代码的评论版本,从优秀评论中获取并添加(许多)必要的更改以处理字符串而不是整数。
(请允许我这个小咆哮:从开始提供实际的样本输入真的会节省很多时间。)
它确实没有段错误(至少不适合我),没有错误和没有奇怪的价值。 输出(即输入文件的新内容):

Damro
Duriyan
Evoks
Godrej
Luxxe
Nilkamal
Wipro
Zuari

代码:

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

typedef char brandname[20];

void sort(brandname *sorted, int count, brandname *value){
    int i=0;
    strncpy((char*)sorted[count], (char*)value, sizeof(brandname));
    if(count == 0) return;

    // picking up input by BLUEPIXY;
    // this probably prevents the segfault,
    // it definitly prevents strange values
    // appearing in the sorted result
    for(i=count;i>0;i--)
    {
        if(0>strncmp((char*)value, (char*)sorted[i-1],sizeof(brandname)))
            strncpy( (char*)sorted[i], (char*)sorted[i-1], sizeof(brandname));
            else break;
    }
    strncpy((char*)sorted[i], (char*)value, sizeof(brandname));
}
int main(int argc,char *argv[]){
    FILE *fp = NULL;
    brandname sorted[1024];
    brandname value;
    int count = 0;
    int i=0;
    fp = fopen("brandlist.txt","r+");
    //fp = fopen("brandlist.txt","w");
    if(NULL == fp){
        perror("fopen");
        exit(0);
    }
    // picking up input from cooments on feof
    // but also use the increasing "count"
    // instead of unchanging "i"
    while(1==fscanf(fp,"%s", value))
    {
        // use the read value inside "sorted[count]"
        sort(sorted, count, &value);
        ++count;
    }
    // do not append sorted to input
    rewind(fp);
    for(i=0;i<count;i++){
        fprintf(fp,"%s\n",sorted[i]);
    }

    if(fp){
        fclose(fp);
        fp = NULL;
    }

    // avoid a warning
    return 0;
}