【问题标题】:Sort numbers from a .txt file in C在 C 中对 .txt 文件中的数字进行排序
【发布时间】:2020-09-12 04:53:09
【问题描述】:

我做了一个排序算法,当我需要排序的数字在代码中的数组中时,它可以正常工作,如下所示:

int sort[] = {16,8,23,4,42,15};

但是我需要代码来对 .txt 文件中的数字进行排序,我确实知道文件的大小(因此不需要 sizeof 来知道您需要排序多少个数字)但问题是文件中的数字不是用逗号分隔的,只有空格,而且我不知道如何让我的代码对这个数字列表进行操作。

我的代码是这样的,就像我说的,当数字的排序数组在以逗号分隔的代码内时,它可以工作:

int main(){

    int temp, size;
    int sort[] = {16,8,23,4,42,15};
    size = sizeof(sort) / sizeof(int);

    for(int j = 0; j < size; j++){
        for(int i = 0; i < size; i++){
            if(sort[i] > sort[i+1]){
                temp = sort[i];
                sort[i] = sort[i+1];
                sort[i+1] = temp;
            }
        }
    }

    for(int p = 0; p < size; p++){
        printf("%d ", sort[p]);
    }
}

而且我也知道用 C 打开文件的代码是这样的:

FILE* f;
f = fopen("1000.txt", "r");
if(f == 0){
    printf("Database unavaible or corrupted\n\n");
    exit(1);
}

但我不知道下一步该做什么,我如何获取这个未排序的数字而不用逗号分隔的文件,并使我的代码排序并打印它们?

【问题讨论】:

    标签: c file sorting


    【解决方案1】:

    您可以使用fscanf 从文件中读取数字,然后将这些数字存储在一个数组中。最后,您可以使用排序函数对 this 数组进行排序。

    以下代码是从文件中读取数字的示例:

    #include <stdio.h>
    #define MAX_NUM 10
    
    int main() {
        FILE * fp = fopen("input.txt", "r");
        if(!fp) {return -1;}
        int array[MAX_NUM] = {0}; // you can use array[size] if you know exactly how many numbers in the file 
        int i = 0;
        while(i < MAX_NUM && fscanf(fp, "%d", &array[i]) == 1) {
            printf("a[%d] = %d\n", i, array[i]);
            i++;
        }
    
        // sort the array here as you did in your code
        return 0;
    }
    

    OT,你的代码在for循环中有错误:

    for(int i = 0; i < size; i++){
       if(sort[i] > sort[i+1]){...}
       ...
    }
    

    i = size - 1 时,sort[i+1] 将变为数组sort[size] 之外的sort,因为您可以访问的最大索引是size-1 而不是size。它应该更改为:

    for(int j = 0; j < size; j++) {
        for(int i = 0; i < size-j-1; i++) {...}
    }
    

    【讨论】:

      【解决方案2】:

      读取数字可以使用fscanf,但还是有内存分配的问题。

      假设文件有 20 个元素,但 MAX_NUM 为 4096,您将不必要地占用 4086*4 字节的内存。 另一方面,该文件可以包含 8000 个元素,但您只能存储 4096 个。 你可以做的是动态内存分配。

      int *array = (int*)malloc(10*sizeof(int));
      unsigned numbers_counter = 0;
      
      while(fscanf(f,"%i",&array[numbers_counter++])==1){
          if(numbers_counter>=sizeof(array)){
              if((array = (int*) realloc(array,sizeof(int)*sizeof(int)*10)) == NULL)
                  exit(1);
          }
      }
      

      我在此段中所做的是在内存上分配 10 个 int 的空间,然后,当数组已满 (if(numbers_counter&gt;=sizeof(array))) 时,数组会用于更大的数字集。 如果你有直到 10 个数字,它只占用 10*4 字节,从 11 到 100 它占用 100*4,等等。

      【讨论】:

        猜你喜欢
        • 2012-05-23
        • 2019-11-19
        • 2020-08-04
        • 2020-10-09
        • 2021-12-22
        • 1970-01-01
        • 2017-07-16
        • 2014-05-18
        • 2012-11-01
        相关资源
        最近更新 更多