0

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.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
Standby
  • 3
  • 2
  • 1
    Check your `fscanf` call. It is simply wrong. – Eugene Sh. Mar 07 '22 at 16:14
  • I don't see how your code can produce the output you posted. As Eugene said, your fscanf() function is, well...dysfunctional. Have you listed the actual output of your program? – mzimmers Mar 07 '22 at 16:20

1 Answers1

0

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?.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256