I am trying to read in a certain portion of a file and that amount of data is different per line but I know how how many bytes of info I want. Like this:
5bytes.byte1byte2byte3byte4byte5CKSum //where # of bytes varies for each line (and there is no period only there for readability)
Actual data:
05AABBCCDDEE11
03AABBCC22
04AABBCCDD33
So I want to have my width be a variable like this:
fscanf_s(in_file,"%variableX", &iData);
Is this possible, because right now I'm thinking I have to create a case statement?
Unfortunately, no, there's no modifier like '*' for printf that causes scanf to get its field width or precision from a variable. The closest you can come is dynamically creating the format string:
char format[8];
sprintf(format, "%%%dX", width);
fscanf(in_file, format, &iData);
If you really want to be able to adjust the fscanf format programmatically, you could try stack-allocating a string with enough space, and then generating the format like so: e.g.
char formatString[100];
// writes "%max_size[0-9]", substituting max_size with the proper digits
sprintf(formatString, "%%%d[0-9]", MAX_SIZE);
fscanf(fp, formatString, buffer); // etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With