首页 > 解决方案 > C 编程 - 从文件中选择排序(运行失败)

问题描述

我必须编写一个程序,在文本文件中按长度对引号进行排序并将结果输出到另一个文件。但是,虽然编译工作并且构建没有错误,但我仍然得到意想不到的结果,加上 netbeans 中的运行错误:

void read_in(char** quotes, size_t* size){
*size = 0;
FILE *filePointer;
filePointer = fopen("quotes.txt", "r");

if (filePointer == NULL){
    perror("Error: File cannot be opened! \n");
    exit(1);
}

char tempArr[MAX_LEN];

while(fgets(tempArr, sizeof(tempArr), filePointer)){
    if(*size == MAX_QUOTES){
        printf("Warning: File contains more than 7 quotes. Load halted. \n");
        return;
    }

    char* ptrMem = (char*)malloc(sizeof(char) * strlen(tempArr));

    if(!ptrMem){
        printf("Error: Memory could not be allocated! \n");
        return;
    }

    strcpy(ptrMem, tempArr);
    ptrMem[strcspn(ptrMem, "\n")] = '\r';
    quotes[(*size)++] = ptrMem;

}  
fclose(filePointer);
}

//-----------------------------------------------------------------------------------------------

void selection_sort(char **quotes, size_t size){
// Current min value to compare
int minValue;
printf("--- Input:\n");   

// Loop and print quotes from array
for(int i = 0; i < (size - 1); i++){                
    printf("%s\n", quotes[i]);
}

for(int i = 0; i < (size - 1); i++){
    // Determine minimum element
    minValue = i ;
    for(int j = i + 1; j < size; j++) {
        if(strlen(quotes[j]) < strlen(quotes[minValue])){              
            minValue = j;
        }              
        swap(&quotes[minValue], &quotes[i]);      
    }                  
}    
}

//-----------------------------------------------------------------------------------------------

void print_out(char** quotes, size_t size){
    printf("--- Output:\n");
        for (int i = 0; i < size; i++){    
        printf("%s\n", quotes[i]);
    }
}

//-----------------------------------------------------------------------------------------------

void write_out(char** quotes, size_t size){
    FILE *filePointer = fopen("output.txt", "w");

// If file ptr null value, throw exception
    if (filePointer == NULL){
        perror("Error: Cannot write to file!");
        exit(1);
    }

for (int i = 0; i < size; i++){
    fprintf(filePointer, "%s\n", quotes[i]);
}

// Close file ptr after use
fclose(filePointer);
}

//-----------------------------------------------------------------------------------------------

void free_memory(char** quotes, size_t size){
// Loop through array of quotes (pointers) and free each allocation
for (int i = 0; i < size ;i++){
    free(quotes[i]);
}  
}

//-----------------------------------------------------------------------------------------------

void swap(char **quote_A, char **quote_B){
    char *temp = *quote_B;
    *quote_A = *quote_B;
    *quote_A = temp;
}

这是我在输出中得到的:在此处输入图像描述

出于某种原因,它一遍又一遍地重复一个字符串(字符指针引号)。它应该做的是让它们按长度排序,这是我的 selection_sort 算法应该做的。所有函数原型都在该代码之上定义。我认为放置整个程序会占用太多空间,但如果需要我可以。

另外,上面定义了main方法和头文件。

编辑:我确实收到了一些关于 strcpy 无法限制为最大缓冲区大小的警告

标签: cruntime-errorselection-sort

解决方案


推荐阅读