Reputation: 15
I'm sorry if this is a dumb question, but I tried many different sources and I'm still not getting what I want. I'm working on a program that reads from a text file, and in the code below, I'm trying to read the first line that will give me the number of resistor color codes were created below it. I'm trying to read the number (n) and simply print it to see that it reads, but I get nothing. It seems so simple, but I can't seem to get it.
`FILE *fpinpt;
FILE *fpoutpt;
FILE *fpnom;
int n, *ptr;
double a, b, c, d, e, f, g, h, i, j, k, l;
fpinpt= fopen("F:\EGR 107\EE\HW 4\resistorInput.txt","r");
fpoutpt= fopen("F:\EGR 107\EE\HW 4\resistorOutput.txt","w");
fpnom= fopen("F:\EGR 107\EE\HW 4\resistorNominal.txt","w");
fscanf(fpinpt,"%d\n",n);
printf("%d",n);
ptr=(int*)calloc(n, sizeof(int));
if (fpinpt==NULL)
{
printf("Error reading resistor file\n");
fclose(fpinpt);
}
if (ptr==NULL) printf("Error, memory not allocated\n");
`
Upvotes: 0
Views: 106
Reputation: 134286
in your code
fscanf(fpinpt,"%d\n",n);
should be
fscanf(fpinpt,"%d",&n);
Also, always check for the return value of fscanf()
, fopen()
to ensure proper input/ operation.
That said, you don't need to cast the return value of malloc()
and family.
Upvotes: 2
Reputation: 53006
The main cause of problems is that you never check for errors. For every fopen()
there must be a
if (fopenedFile == NULL)
ohNoMust_ICannotUse_fopenedFile();
now to why are your fopen()
's failing it's because you haven't escaped the '\'
character, so each file name should fix it like this
"F:\\EGR 107\\EE\\HW 4\\resistorInput.txt"
Then, files will be opened, but fscanf()
will not work because of what the other answer already ("while I was editing mine") addressed.
NOTE:
Please read both answers, it doesn't make sense to repeat what @SouravGhosh already said.
Upvotes: 0