This is an example of how to use the PlayTone, Wait, Stop, TextOut, OpenFileAppend, CloseFile, OpenFileRead, FormatNum, Write, Read, and CircleOut functions.This program is intended to serve as an introduction to data files on the NXT. It focuses on handling the codes returned by the file system's API calls, which is an important aspect of the API that is all too often neglected by programmers. The program deals with a data file describing circles. On each run, it adds a new circle record to the data file. Then it reads in the whole data file and displays all the circles on NXT screen. It creates the data file if doesn't already exist. If you run it several times in seccession, you will fill the data file and get a file-is-full exception. The data flie created by this program is not visible on the NXT. To delete the file, circles.dat, you can use the NeXT Explorer or the example program ex_delete_data_file.nxc.
#define MIN_R 10
#define MAX_R 30
#define MIN_X 20
#define MAX_X 80
#define MIN_Y 10
#define MAX_Y 54
byte handle = 0;
#define FILE_NAME "circles.dat"
#define RECORDS 4
#define RECORD_SIZE 3
#define FILE_SIZE (RECORD_SIZE * RECORDS)
struct circle
{
byte r;
byte cx;
byte cy;
};
void init_circle(circle & c)
{
c.r = MIN_R +
Random(MAX_R - MIN_R);
c.cx = MIN_X +
Random(MAX_X - MIN_X);
c.cy = MIN_Y +
Random(MAX_Y - MIN_Y);
}
void shutdown(const int delay)
{
}
void rtn_code_out(const unsigned int code)
{
}
void open_for_write()
{
unsigned int file_size = FILE_SIZE;
handle = 0;
unsigned int rtn_code =
CreateFile(FILE_NAME, file_size, handle);
switch (rtn_code)
{
return;
break;
default:
rtn_code_out(rtn_code);
break;
}
}
void open_for_read()
{
unsigned int file_size = FILE_SIZE;
handle = 0;
unsigned int rtn_code =
OpenFileRead(FILE_NAME, file_size, handle);
{
rtn_code_out(rtn_code);
}
}
void write_recd(const circle recd)
{
unsigned int rtn_code =
Write(handle, recd);
{
switch (rtn_code)
{
break;
default:
rtn_code_out(rtn_code);
break;
}
}
}
void read_all(circle & recd)
{
while (true)
{
unsigned int rtn_code =
Read(handle, recd);
switch (rtn_code)
{
break;
return;
default:
rtn_code_out(rtn_code);
}
}
}
task main()
{
circle c;
open_for_write();
init_circle(c);
write_recd(c);
open_for_read();
read_all(c);
}