#fscanf values are not correct

6 messages · Page 1 of 1 (latest)

opal oak
#

I am trying to read a csv file that is all integers, and there's no header. The first line is just the first list of integers that I need. Right now I'm trying to read them in with a while loop and add them to an array but I'm getting 0,0 every time and that is not the correct value

char * file = argv[1];
FILE * fp = fopen(file, "r");

if (!fp) {
  printf("File not found!\n");
}

while (fp) {
  int * x = malloc(sizeof(int));
  int * y = malloc(sizeof(int));
  fscanf(fp, "%d,%d", x, y);
  printf("%d, %d\n", *x, *y);
}

The format of the csv is
2,4
13,6
etc.

Update: I removed the while loop and it correctly grabbed the first value, am I incrementing my fp incorrectly or something?

copper moonBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

rare snow
#

First of all you're leaking memory. Instead of

int *x = malloc(sizeof(int));
int *y = malloc(sizeof(int));
fscanf(fp, "%d,%d", x, y);
printf("%d, %d\n", *x, *y);

you should just do:

int x, y;
fscanf(fp, "%d,%d", &x, &y);
printf("%d, %d\n", x, y);
copper moonBOT
#

@opal oak Has your question been resolved? If so, run !solved :)

opal oak
#

!solved