下面的程序在编译时给出以下错误:


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

最佳答案

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

这是代码的注释版本,从出色的注释中挑选出来,并添加(许多)必要的更改以处理字符串而不是整数。
(请允许我说一下:确实可以节省大量时间,从一开始就提供实际的样本输入。)
它确实没有段错误(至少对我而言不是),没有错误输入和没有奇怪的值。
输出(即输入文件的新内容):

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

关于c - C程序从文本文件读取并将已排序的列表写入同一文本文件。我可以做什么修改?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44362348/

10-11 23:03
查看更多