Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Width as a variable when using fscanf [duplicate]

Tags:

c++

c

width

scanf

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?

like image 932
Nick Sinas Avatar asked Jul 22 '10 20:07

Nick Sinas


2 Answers

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);
like image 99
Chris Dodd Avatar answered Oct 23 '22 13:10

Chris Dodd


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...
like image 2
Rose Perrone Avatar answered Oct 23 '22 11:10

Rose Perrone