简体   繁体   中英

C, Reading A Text File

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

`

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM