LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

FmtFile and ScanFile

I save data to file with FmtFile and Retrieve data with ScanFile. It did not work. Please, help.
my code:
char x[20], y[20];
int filehandle;
// to enter string
ScanIn("%l>%s",x);
ScanIn("%l>%s",y);
// save data
filehandle=OpenFile("setup.dat",2,01);
FmtFile(filehandle,"%s<%s[w20]",x);
FmtFile(filehandle,"%s<%s[w20]",y);
CloseFile(filehandle);
//read data
filehandle=OpenFile("setup.dat",1,2,1);
ScanFile(filehandle,"%s>%s[w20]",x);
ScanFile(filehandle,"%s>%s[w20]",y);
CloseFile(filehandle);

What I expect is a string with 20 byte right justifies when I save, so I use the same w20 when I read data.
0 Kudos
Message 1 of 2
(3,679 Views)
I see two problems in your code that can affect its behaviour.
- ScanIn function terminates on a white space, or tab character, so if user inputs for examples the abused "Hello world" string, ScanIn returns only "Hello" in x. To ensure that the whole string is written to the x variable, you must terminate scanning on some particular character, adding for example [t13] to the format string to termnate input on the return key. The format string becomes "%s[t13]" and returns correctly "Hello world" in the example above
- You must limit the user input lenght, in order not to receive the 'Attempt to write past end of string error'. A possible way is to use the 'w' modifier in the format string, paying attention to indicate a littler lenght than the string si
ze, in order to let room for the termionating NULL character at the end of the string. So your format string must be "%s[w19t13]", and that way all should work well.

To right justify your string, the simplest way is to add some extra spaces to the left of the strings before writing them to the file, and add a separator between them (for example a comma), using then the appropriate format string for the ScanFile function ("%s[xt44]%s[xt13]" to separate the strings on the comma and to discard terminators).

The same rules apply (mutatis mutandis) in case you are treating a string generated in the program instead of a user input: attention should be payed to the separator and termination characters both in formatting and scanning. The standard libraries reference manual is a useful guide in that matter.

Roberto


Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
Message 2 of 2
(3,679 Views)