如何读取文件然后存储到数组然后打印?

时间:2015-06-09 09:02:48

标签: c arrays printf scanf

程序的第一部分将整数写入名为'newfile.dat'的文件中。 第二部分“想要”将整数存储到数组中。你能解释一下我试图将整数存储到一个数组中并且打印错误的部分吗?

#include <stdio.h>
#include <conio.h>
#define SIZE 3
int main(void){
    int murray[SIZE];
    int count;
    int n;
    int i;
    FILE*nfPtr;

    if((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","w"))==NULL)
{
    printf ("Sorry! The file cannot be opened\n");
}
    else
{//else 1 begin

    printf("Enter numbers to be stored in file\n");//Here I am writing to the file. It works fine
    scanf("%d\n",&n);
    while (!feof(stdin)){
          fprintf(nfPtr,"%d\n",n);
          scanf("%d",&n);
          }
}//else 1 ends
        fclose(nfPtr);
    if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","r"))==NULL)//Here is where I try to read from file 
{
    printf ("Sorry! The file cannot be opened\n");
}
    else
{//else 2 begin
        fscanf(nfPtr,"%d",&n);
        n=i;//Is this how I can add the file integers to program?
        while (!feof(nfPtr)){
              printf("%d\n",murray[i]);//Is this how I can get the array to print?
              }
        fclose(nfPtr);
}//else 2 ends
getch();
return 0;
}

2 个答案:

答案 0 :(得分:1)

关于从底部开始的第9行。在行n=i;中,您将未初始化的变量i的内容写入n,其中n是您刚读取文件内容的变量。您希望muarray[i]=n;填充数组。

话虽如此,你需要给i一个值。因此,您将其初始化为i=0;。每次填充数组时,您需要使用i = i + 1;i++;增加i。

如果你没有错过,你应该读一下循环和数组的主题。

答案 1 :(得分:0)

这个发布的代码:

    if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","r"))==NULL)//Here is where I try to read from file 
{
    printf ("Sorry! The file cannot be opened\n");
}
    else
{//else 2 begin
        fscanf(nfPtr,"%d",&n);
        n=i;//Is this how I can add the file integers to program?
        while (!feof(nfPtr)){
              printf("%d\n",murray[i]);//Is this how I can get the array to print?
              }
        fclose(nfPtr);

只调用一次fscanf()。它需要每次循环调用fscanf()。

建议:

if ((nfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\newfile.dat","r"))==NULL)//Here is where I try to read from file 
{
    perror("Sorry! newfile.dat cannot be opened for reading\n");
}
else
{//else 2 begin
    while ( 1 == fscanf(nfPtr,"%d",&n))
    {
        printf("%d\n",n);  // cannot use uninitialized array: murry[]
    }
    fclose(nfPtr);
} // end if