c - fscanf not scanning any numbers -


i developing simple c application. takes single file command line argument, formatted like:

1,2,3 4,5,6 7,8,9 etc. 

however, whatever reason, fscanf never scans numbers! here example:

#include <stdio.h>  int main(int argc, char **argv) {     file *file = fopen(*argv, "r");     int i1, i2, i3;     while (fscanf(file, "%d,%d,%d", &i1, &i2, &i3) == 3) {         printf("doing stuff %d, %d, , %d...\n", i1, i2, i3);     }     fclose(file);     return 0; } 

if run filename argument, exits, due fscanf returning 0. i've tried several variations of this, no avail. how make fscanf read numbers correctly?

superficial answer: wrong file opened code should have used argv[1] rather *argv.

let deeper.

code had troubles , lacked error checking in @ least 2 places.

  1. file *file = fopen(*argv, "r"); not followed test on file. classic check not have detected op's problem file, executable, open-able.

  2. the return value fscanf(file, "%d,%d,%d", &i1, &i2, &i3) lightly tested. return values of eof 0 1 2 3 possible yet eof 3 expected. had code tested non-eof 3, problem have rapidly been found.

lesson learned: insure code, mis-behaving code, has adequate error checking. saves coder time in long run.

#include <stdio.h>  int main(int argc, char **argv) {   if (argc != 2) {     fprintf(stderr, "unexpected argument count %d.\n", argc);     return 1;   }    file *file = fopen(argv[1], "r");   if (file == null) {     fprintf(stderr, "unable open file: \"%s\"", argv[1]);     return 1;   }    int i1, i2, i3;   int n;   while ((n = fscanf(file, "%d,%d,%d", &i1, &i2, &i3)) == 3) {     printf("doing stuff %d, %d, , %d...\n", i1, i2, i3);   }   if (n != eof) {     fprintf(stderr, "unexpected scan failure count %d\n", n);     return 1;   }   fclose(file);   return 0; } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -