Reading and Writing
Files in persistent storage are accessed in a program in one of two modes: read or write. Inwrite mode, data can be written to the le. In read mode, data can be read from the le. A
le cannot be in read and write mode simultaneously. The mode is determined at the time
the le is opened.
A le in persistent storage is identied by its lename. However, within a program, for
the sake of readability, a le is identied by its lehandle. A lehandle is a variable that
represents the external le. All references to the le are made through the lehandle. A
lehandle variable must be declared as type TFileHandle. A second special datatype for
use with les is the TFileIOResult type. A variable of type TFileIOResult is capable
of holding error messages related to various le operations. For example, if the program
attempts to open a le in read mode and the le does not exist, the program will not crash.
Instead the error will be reported in the TFileIOResult variable. A careful programmer
can check the error message and oer the user alternatives to resolve the problem instead of
allowing the program to crash.
# pragma config ( Sensor , S1 , Light , sensorLightInactive )
const string FILENAME = " lightreadings .dat ";
const int NUMSAMPLES = 97;
const int SAMPLEINTERVAL = 15; // in minutes
task main () {
TFileIOResult nIOResult ;
TFileHandle LIGHTFILE ;
int FileSize = 2* NUMSAMPLES ;
int i,j;
OpenWrite ( LIGHTFILE , nIOResult , FILENAME , FileSize );
for (i=1;i <= NUMSAMPLES ;i ++) {
WriteShort ( LIGHTFILE , nIOResult , SensorValue [ Light ]);
for (j =0;j< SAMPLEINTERVAL && i!= NUMSAMPLES ;j++) {
wait10Msec (6000); // one minute
}
}
Close ( LIGHTFILE , nIOResult );
}
Listing 9.1: This program records light level readings to a le at 15 minute intervals for a
full day.
# pragma config ( Sensor , S1 , Light , sensorLightInactive )
const string FILENAME = " lightreadings .dat ";
const int NUMSAMPLES = 97;
task main () {
TFileIOResult nIOResult ;
TFileHandle LIGHTFILE ;
int FileSize = 2* NUMSAMPLES ;
int i,n;
OpenRead ( LIGHTFILE , nIOResult , FILENAME , FileSize );
for (i=1;i <= NUMSAMPLES ;i ++) {
ReadShort ( LIGHTFILE , nIOResult ,n);
nxtDrawLine (i ,0,i,n);
}
Close ( LIGHTFILE , nIOResult );
wait10Msec (1000);
}
Listing 9.2: This program displays the light readings found in the le.


No comments:
Post a Comment