首页 > 解决方案 > C 编程/Linux - 读取和写入文件时输出不正确?

问题描述

我正在 Linux 中编写一个 C 程序,它将读入一个数字列表,对它们进行排序,然后将它们输出到一个文本文件中。我的程序编译得很好,但是我的输出……有点奇怪。我刚刚开始用 C 进行编码,所以我对这个错误可能来自哪里有点不知所措。

我写的输入文本文件:

4 3 2 1

我的代码:

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

void sortNum(int *num, int count){
    int i,j;
    for(i=0;i<=count;i++){
        int minIndex=i;
        for(j=i+1;j<=count;j++){
            if(num[j] < num[minIndex]){
                minIndex=j;
            }
        }
        int temp = num[minIndex];
        num[minIndex]=num[i];
        num[i]=temp;
    }
}

int main(int argc, char *argv[]){
    int *numbers;
    int count=0;
    int i=0;
    char input[20], output[20];
    FILE *fileIn, *fileOut;

    numbers = (int *)malloc(sizeof(int));
    if(argc != 3){
        printf("Please provide the input and output text file names as %s name1 name2\n", argv[0]);
        return 0;
    }
    else{
        sscanf(argv[1], "%s", input);
        sscanf(argv[2], "%s", output);
    }

    fileIn = fopen(input, "r");
    fileOut = fopen(output, "w");

    if(!fileIn){
        printf("Input file %s cannot be opened.\n", input);
        return 0;
    }
    else if(!fileOut){
        printf("Output file %s cannot be written.\n", output);
        return 0;
    }
    else{
        while(!feof(fileIn)){
            i++;
            numbers = (int *)realloc(numbers, 4 * sizeof(int));
            fscanf(fileIn, "%d", &numbers[i]);
            printf("%d ", numbers[i]);
        }
    }
    count = i;
    free(numbers);
    fclose(fileIn);
    printf("\n");
    sortNum(numbers, count);
    printf("\nElements are now sorted: \n");

    for(i=0; i <= count; i++){
        fprintf(fileOut, "%d", numbers[i]);
        printf("%d ", numbers[i]);
    }
    printf("\n");
    fclose(fileOut);
    return 0;
}

这是我运行程序时得到的输出:

4 3 2 1 134409 Elements are now sorted: 0 1 2 3 4 134409

对于初学者来说,我不确定0写作时从哪里来,也不知道134409应该代表什么或代表什么。

如果正确完成,所需的输出应该类似于:

4 3 2 1 Elements are now sorted: 1 2 3 4

就故障排除而言,我真的希望我能提供更多,但我真的迷路了。也许我忽略了库函数的某些内容?我最初认为这可能与我编写 while 循环的方式有关,但现在我不太确定。我真的很感激一些指导。

标签: c

解决方案


推荐阅读