c - 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 循环的方式有关,但现在我不太确定。我真的很感激一些指导。
解决方案
推荐阅读
- python - Pandas Dataframe 对内存来说太大,实现 dask 的问题
- php - 添加/合并 json 数组
- java - Spring Junit 数据库连接丢失
- collections - 在过滤一些键时将 HashMap 转换为 IntArray
- ruby - 如何在 ruby 中使用 or(||) 运算符连接整数数组?
- docker - 在 Kubernetes 部署中指定镜像必须以交互模式运行
- android - 任务 ':app:transformClassesWithAndroidGradleClassShrinkerForDebug' 执行失败
- c++ - 调整向量大小以检索值,这是正确的还是在任何情况下都可能导致段错误?
- python - 如何在 Pandas 中创建新列,条件是按另一列的值重复?
- google-cloud-platform - 升级计算引擎实例上的操作系统