-
在此程序中,我想让用户输入2个参数,数字 整数和文件名。
- 该文件具有10行的整数值。
- 阅读文件,然后将其放在inarray []; 上
,然后将其输出为末端;
注意:对于完整的程序,我想制定一个程序 将扫描文件由随机整数组成,然后排序 它们按顺序升级,并打印出前10% 分类整数。
错误:目前,我要测试它是否可以读取文件并放置值 正确地进入了埋葬,但它不断遇到错误。
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("%xn",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("%dn",nums[i]);
return 0;
}
如果此文件是prog.c
,并且相应的可执行文件为prog
,并且您的数字文件称为nums.txt
,并且包含100
整数,则将其称为
prog nums.txt 100
采用参数的优点是,它使以后重复命令更加容易(重复它所需的所有信息都将在shell的命令历史记录中),并且它是将参数传递到的标准方式一个程序。它还可以释放其他用途的标准输入。
您确实对文件名管理有问题。char
用于字符;如果要处理文件名,则必须使用字符串。在C中,我们可以使用由NUL-Character终止的char
数组。在这里,由于argv[2]
直接保留名称,因此您可以简单地使用指针。
char *fileName = argv[2];
,然后:
fopen(fileName, "r");
由于您不修改argv
指针,也可以将argv[2]
直接发送为参数。
我在您的代码中看到的问题之一是:
char fileName="";
sscanf(argv[2],"%c",&fileName)
字符串文字为 contand 字符串,这意味着您不应该尝试修改它,您应该对该字符串使用静态(或动态)char阵列并使用%s
格式指示符,或者仅将文件名为argv [2]
char *fileName;
fileName = argv[2];