c中的文件处理

时间:2015-06-11 18:08:39

标签: c file-handling

我创建了一个简单的程序来读取值的值,然后从文件中读取这些值并将它们存储在数组中并打印数组的值。

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

void main(){
    int i=0,j=0,n,no[n];
    FILE *fp=fopen("input.txt","r");
    if(fp==NULL)
        printf("File input error\n");
    else{
        fscanf(fp,"%d",&n);
        *no=(int *)malloc(n*sizeof(int));
        while(i<n){
            fscanf(fp,"%d",&no[i]);
            printf("%d\t",no[i]);
            i++;
        }
    }
}

我的输入文件如下

  

10 37 21 55 52 68 97 02 00 103 84

我得到的输出是

  

37 21 55 52 68 97 2 0

为什么我会看到这个输出?

2 个答案:

答案 0 :(得分:2)

该行

    *no=(int *)malloc(n*sizeof(int));

不对。我很惊讶你的编译器没有警告你。

*no的类型为int。您正在指定一个指向int的指针。

使用gcc,我收到以下警告。

soc.c: In function ‘main’:
soc.c:11:12: warning: assignment makes integer from pointer without a cast
         *no=(int *)malloc(n*sizeof(int));

此外,该行

int i=0,j=0,n,no[n];

不正确。在用于定义n之前,no未初始化。

这是您的计划的更新版本,应该有效。

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

void main(){
   int i=0,j=0,n;
   int* no;
   FILE *fp=fopen("input.txt","r");
   if(fp==NULL)
      printf("File input error\n");
   else{
      if ( fscanf(fp,"%d",&n) == 1 )
      {
         no = malloc(n*sizeof(int));
         while(i<n){
            if ( fscanf(fp,"%d", &no[i]) == 1 )
            {
               printf("%d\t",no[i]);
            }
            else
            {
               // Unable to read the number.
               // Get out of the loop.
               break;
            }
            i++;
         }
      }
      else
      {
         // Unable to read n.
         // Print some message to indicate the error
      }
   }
}

答案 1 :(得分:0)

在您的代码中,您尝试读取n个元素而不检查EOF。 您应该添加一个条件,将fscanf与扫描元素的数量进行比较(在本例中为1),从而避免在不知不觉中达到EOF。