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;
}
About the 9th line from the bottom. In line
n=i;
you write the content of the uninitialized variablei
ton
, wheren
is the variable you just read the content of the file into. You wantmuarray[i]=n;
to fill the array.That being said, you need to give a value to
i
. So you initialize it toi=0;
. And everytime you filled the array you need to increment i withi = i + 1;
ori++;
.If you didn`t just miss that, you should read in on the topic of loops and arrays.