warning: passing argument 1 of ‘fscanf’ discards ‘const’ qualifier from pointer target type

Viewed 257

I'm opening a file and it won't change so I put the const keyword before it. The compiler, though, gives me this warning. Why doesn't fscanf accept const files?

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

int main(void){
  const FILE *realNumbers=fopen("float.txt", "r");
  if(realNumbers==NULL){
    fprintf(stderr, "Could not open the file.\n");
    return 1;
  }
  unsigned int realNumbersSize=1;
  float *realNumbersArray=malloc(realNumbersSize*sizeof(float));
  if(realNumbersArray==NULL){
    fprintf(stderr, "Could not allocate memory.\n");
    return 2;  
  }
  for(int i=0;fscanf(realNumbers, "%f", &realNumbersArray[i])==1;i++){
    realNumbersSize++;
    realNumbersArray=realloc(realNumbersArray, realNumbersSize*sizeof(float));
    if(realNumbersArray==NULL){
      fprintf(stderr, "Could not reallocate memory.\n");
      return 3;  
    }
  }
  free(realNumbersArray);
  fclose(realNumbers);
  return 0;
}
1 Answers

Your file won't change. But FILE is not your actual file. It is a structure that tracks the state of a file with respect to what you have done to it in your code. It can't be const as fscanf will need to update it (e.g. to track the read position). – kaylum

Related