在这个程序中,我想让用户输入 2 个参数,数字 整数和文件名。
- 文件有 10 行整数值。
- 读取文件,放入inArray[];
然后作为结尾输出;
注意:对于完整的程序,我想制作一个程序 会扫描一个由随机整数组成的文件,然后排序 它们按升序排列,并打印出前 10% 的排序整数。
错误:现在,我想测试它是否可以读取文件并输入值 正确地进入 inArray,但它不断出错。
warning: initialization makes integer from pointer without a cast findTotal.c:43:6: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast /usr/include/stdio.h:271:14: note: expected ‘const char * __restrict__’ but argument is of type ‘char’
请帮帮我,谢谢
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int numOfInt;
char fileName="";
sscanf(argv[1],"%d",&numOfInt);
sscanf(argv[2],"%c",&fileName);
int i, rc;
/* the origninal list , initialise as 0 index*/
int inArray[numOfInt];
/* the number of output int */
int outNumInt = numOfInt * 0.1;
/* the output array of int */
int outArray[outNumInt];
FILE *inFile;
inFile = fopen(fileName,"r");
/* check if the file is empty */
if(inFile==NULL){
printf("can not open the file");
}
for (i = 0; (rc = getc(inFile)) != EOF && i < numOfInt; inArray[i++] = rc)
{
}//for
fclose(inFile);
for(i = 0; i < numOfInt;i++){
printf("%x\n",inArray[i]);
}
}//main
最佳答案
我认为您可以在这里更好地使用 scanf。您使用它来读取两条本应作为参数传递给程序的信息,然后避免将其用于实际有用的地方,即读取有问题的文件。这是我对此的看法:
#include <stdlib.h>
#include <stdio.h>
int cmp(const void *a, const void *b) { return *(int*)b - *(int*)a; }
int main(int argc, char *argv[])
{
char * ifile = argv[1];
int n = atoi(argv[2]), m = n/10, i;
int nums[n];
FILE * f = fopen(ifile, "r");
for(i = 0; i < n; i++) fscanf(f, "%d", &nums[i]);
qsort(nums, n, sizeof(int), cmp);
for(i = 0; i < m; i++) printf("%d\n",nums[i]);
return 0;
}
如果这个文件是prog.c
,相应的可执行文件是prog
,你的数字文件叫做nums.txt
,并且包含 100
个整数,您可以称其为
prog nums.txt 100
以这种方式接受参数的优点是它使得以后重复命令更容易(重复它所需的所有信息都将在 shell 的命令历史中),并且这是将参数传递给的标准方式一个程序。它还释放了标准输入以用于其他用途。
关于c - 读取 10 行整数的文件,将它们放入数组中,并输出数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221106/