How to read a file then store to array and then print?

78 views Asked by At

The first part of program writes the integers to a file called 'newfile.dat'. The second part 'wants' to store the integers into array. Can you please explain what part of my attempt to store my integers into an array and print is wrong?

#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

There are 2 answers

0
MisterC On

About the 9th line from the bottom. In line n=i; you write the content of the uninitialized variable i to n, where n is the variable you just read the content of the file into. You want muarray[i]=n; to fill the array.

That being said, you need to give a value to i. So you initialize it to i=0;. And everytime you filled the array you need to increment i with i = i + 1; or i++;.

If you didn`t just miss that, you should read in on the topic of loops and arrays.

0
user3629249 On

this posted code:

    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);

only calls fscanf() one time. It needs to call fscanf() every time through the loop.

suggest:

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