读取10行整数的文件,将它们放入数组中,然后输出数组

时间:2012-11-04 17:39:07

标签: c

  1. 在这个程序中,我想让用户输入2个参数,即数字       整数和文件名。

    1. 该文件有10行整数值。
    2. 读取文件,并将其放入inArray [];
    3. 然后将其输出为结尾;

      注意:对于完整的程序,我想制作一个程序       将扫描文件包含随机整数,然后排序       它们按升序排列,并打印出前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’
      
  2. 请帮帮我,谢谢

    #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
    

3 个答案:

答案 0 :(得分:1)

我认为你可以在这里更好地使用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的命令历史中),并且它是传递参数的标准方法一个程序。它还释放了其他用途的标准输入。

答案 1 :(得分:0)

我在您的代码中看到的一个问题是:

 char fileName="";
 sscanf(argv[2],"%c",&fileName)

字符串文字是常量字符串,这意味着您不应该尝试修改它,您应该为该字符串使用静态(或动态)char数组并使用{{1格式说明符,或者只是将fileName指向argv [2]

%s

答案 2 :(得分:0)

文件名的管理确实存在问题。 char用于字符;如果要处理文件名,则必须使用字符串。在C中,我们可以使用char数组,以空字符结尾。这里,由于argv[2]直接包含名称,因此您只需使用指针即可。

char *fileName = argv[2];

然后:

fopen(fileName, "r");

由于您不修改argv指针,您也可以直接发送argv[2]作为参数。

相关问题