Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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",id,&password);

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I would be very appreciated to your help.

>Solution :

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,"%19s,%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," %19[^,\n],%d");

Check return value

if (fscanf(filep," %19[^,\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?.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading