views:

94

answers:

4

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?

A: 

fscanf with %X will stop at a newline automatically, right? If the fields really are newline-terminated (as in your example), then can't you just call

fscanf(in_file, "%X", &iData);

and let fscanf figure out where the end is?

SCFrench
Yes thats right I actually made a mistake there is a checksum at the end that I don't want. So this wouldnt work for me.
Nick S.
+3  A: 

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);
Chris Dodd
You have in+file, that should be in_file.
SCFrench
A: 

You might also consider using C++ streams.

#include <ifstream>
#include <iostream>

// open the file and create a file input stream
ifstream file("test.txt" , ios::in | ios::binary);

// loop through the whole file
while (ifs.good())
{
    // extract one byte as the field width
    unsigned char width;
    file.read(&width, 1);

    // extract width number of unformatted bytes
    char * bytes = new char[width];
    file.read(bytes, width);

    // process the bytes
    ...
    delete [] bytes;

    // skip EOL characters if needed
    // file.seekg(1, ios_base::cur)
}

file.close();

A simpler way if the newlines are included as you seem to indicate, would be to use getLine(). Check out http://www.cplusplus.com/reference/iostream/ifstream/ for more ways to use read(), get(), getLine() and lots of other great stream functions.

gnathan
A: 

I think the simplest would be to use fread() like this:

fread(buffer, nbytes, sizeof(char), in_file);
ahy1