LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Formatting integers to/from file

Hi all,

Could someone please tell me what is wrong with this code, in which I try to write 8 integers to a file and them read them back in?

I've found out that the "rep code" only applies to integer _arrays_, and that if I format each integer out one at a time using "%i<%i" it works.

But how do I format multiple parameters in one call to FmtFile?

Thx,
Ian


int chk[8], i, filehw, filehr;
filehw = OpenFile ("test.dat", VAL_WRITE_ONLY, VAL_TRUNCATE, VAL_BINARY);
FmtFile(filehw, "%i%i%i%i%i%i%i%i", 1,3,5,7,11,13,17,19);
CloseFile(filehw);

filehr = OpenFile ("test.dat", VAL_READ_ONLY, VAL_TRUNCATE, VAL_BINARY);
for (i=0; i< 8; i++){
ScanFile(filehr, "%i>%i", &chk[i]);
}
CloseFile(filehr);
0 Kudos
Message 1 of 4
(3,538 Views)
The problem is that when you are scanning back in, you need some way to distinguish between the values written out. If you put spaces between the %i format specifiers in the FmtFile call, you will get the behavior you expect.

ie.

FmtFile(filehw, "%i %i %i %i %i %i %i %i", 1, 3, 5, 7, 11, 13, 17, 19);

Regards,

-alex
0 Kudos
Message 2 of 4
(3,538 Views)
Two things; to make my original answer work you also have to change ScanFile format specifier to %s>%i (since not specifying the source in the FmtFile call implicitly formats the numbers as strings).

However, if you want the file written in binary (as I realized you were trying to do), this should work:


int chk[8], i, filehw, filehr;
filehw = OpenFile ("test.dat", VAL_WRITE_ONLY, VAL_TRUNCATE, VAL_BINARY);
FmtFile(filehw, "%8i<%i%i%i%i%i%i%i%i", 1,3,5,7,11,13,17,19);
CloseFile(filehw);

filehr = OpenFile ("test.dat", VAL_READ_ONLY, VAL_TRUNCATE, VAL_BINARY);
for (i=0; i< 8; i++)
ScanFile(filehr, "%i>%i", &chk[i]);
CloseFile(filehw);

Regards,

-alex
Message 3 of 4
(3,538 Views)
Brilliant! It was that magic combination of a rep code (8) in the target specifier and separate "%i"s in the source specifier that was eluding me.

Many thanks.
0 Kudos
Message 4 of 4
(3,538 Views)