You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言统计文本文件整数并排序写入文件的代码问题排查

问题:统计文件整数数量并排序写入文件

我创建了名为qsort.txt的文本文件,其中写入了35个整数。我的目标是:

  • 统计该文件中的整数数量
  • 将整数存入malloc()分配的数组中
  • 使用qsort()进行排序
  • 将排序后的数字写入名为sorted.txt的文本文件
  • 让代码更灵活,通过FILE *fa = fopen(argv[1], "r+")中的argv[1]指定任意待排序的文本文件

目前我卡在统计文件中的整数数量这一步,以下是我编写的第一段代码,但未达到预期效果:

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

int compare(const void *a, const void *b) {
    if (*(int*)a < *(int*)b)
        return -1;
    else if (*(int*)a > *(int*)b)
        return 1;
    else
        return 0;
}

int main(int argc, char **argv) {

    FILE *fa = fopen(argv[1], "r+");
    if (!fa)
        exit(1);
    FILE *fb = fopen("sortirano.txt", "w+");

    long duljina, i;
    long *ptr, *zapis;
    long count = 0;

     while (!feof(fa))
         count++;

     printf("%lu\n", count);

     fseek(fa, 0, SEEK_END);
     duljina = ftell(fa);
     fseek(fa, 0, SEEK_SET);

     ptr = (long *)malloc(sizeof(long));

     while (!feof(fa)) {
         fscanf(fa, "%lu", ptr);
         count++;
     }
     printf("count: %lu\n", count);
     for (i = 0; i < count; i++)
         printf("%lu ", ptr[i]);

    printf("\n");

    free(ptr);

    fclose(fa);
    fclose(fb);

    return 0;
}

编辑补充:以下是我编写的更简洁的代码,但运行后输出结果全为0,仍无法正常工作:

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

int compare(const void *a, const void *b) {
    if (*(long*)a > *(long*)b)
        return 1;
    if (*(long*)a < *(long*)b)
        return -1;
    else
        return 0;
}

int main() {
    FILE *fa = fopen("qsort.txt", "r"); assert(fa != NULL);
    FILE *fb = fopen("sorted.txt", "w+"); assert(fa != NULL);

    long *ptr;
    long save;
    long count = 0;
    long i;
    long k;

    while ((fscanf(fa, "%ld", &save)) == 1) //统计元素数量
        prebroji++;

    printf("count: %ld\n", count); //检查统计的元素数量是否正确

    ptr = (long *)malloc(count * sizeof(long)); //分配内存

    for (i = 0; i < count; i++)
        fscanf(fa, "%ld", &ptr[i]);

    for (i = 0; i < count; i++) //检查整数是否存入数组
        printf("%ld ", ptr[i]);

    qsort(ptr, count, sizeof(long), compare);

    for (i = 0; i < count; i++) //检查排序结果
        printf("%ld ", ptr[i]);

    for (i = 0; i < count; i++)
        fprintf(fb, "%ld", ptr[i]);

    printf("\n");

    free(ptr);
    fclose(fa);
    fclose(fb);

    return 0;
}

内容的提问来源于stack exchange,提问作者tux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:40:58