Home > OS >  Can I use fscanf to read a character array and an integer seperated with a comma in my file.txt (in
Can I use fscanf to read a character array and an integer seperated with a comma in my file.txt (in

Time:03-08

I don't know much about file handling in C. In my file.txt the first row is like this:

25031470760,1234

I want to read them seperately such as:

FILE* filep = fopen("myfile.txt","r");
char id[20];
int password;
fscanf(filep,"%s,%d");

I want id = 25031470760 and password = 1234 but when i print them:

printf("%s %d",id,password); the output is ridiculously this : 25031470760,1234 2201625031470760,1234 22016

I would be very appreciated to your help.

CodePudding user response:

fscanf(filep,"%s,%d"); fails in various ways.

No width limit

"%s" is subject to overrun. Use a width limit

char id[20];
...
fscanf(filep,"s,%d");

Won't stop on ,

"%s" will read and save ','. Consider " %[^,\n]" to 1) skip leading white-space and then 2) save all non-comma, non-end-of-line characters.

fscanf(filep," [^,\n],%d");

Check return value

if (fscanf(filep," [^,\n],%d") == 2) {
  Success();
} else {
  Fail();
}

Missing check of fopen() success

FILE* filep = fopen("myfile.txt","r");
if (filep == NULL) {
  puts("File to open");
  return fail;  // Illustrative code.
}

Perhaps other issues

Given OP's 2 outputs, I suspect Why is “while ( !feof (file) )” always wrong?.

  • Related