dimanche 12 avril 2009

Using libfat

The example in de devkitpro prints the directory of the card.
It only runs on the ds itself, not in the emulator i use....:-(

ok this is a diary, just stating the things needed and where i found these: i needed to read in the integers describing the points of the triangulation for the minigolf game fields.

the libfat example only described reading the directory.

I found an example of really reading in a textfile here: (actually it is written for the wii, but who cares?)
http://www.codemii.com/2009/03/02/tutorial-10-using-the-filesystem/

and the functions to read a txt file are: (adding to the example in the devkitpro)


void die(char *msg) {
perror(msg);
fatUnmount(0);
exit(0);
}

void readFile()
{
FILE *f = fopen ("hello.txt", "rb");// If file doesn't exist or can't open it then we can grab the latest file
if (f == NULL) {
die("Could not open myfile.txt file for reading.\n");
}

else {
char file_line [20];
int line_number = 0;
while (fgets (file_line, 20, f)) {
printf("Line %i: %s\n",line_number, file_line);
line_number++;
}
fclose(f);
}
}

as explained (and needed for my minigolf, reading in the triangulations of the fields)
you can easily read in and distribute integers to arrays lik this:

make these arrays global, for instance

int x_pos[] = { 0, 0, 0, 0, 0};
int y_pos[] = { 0, 0, 0, 0, 0};

void readFile()
{
FILE *f = fopen ("hello.txt", "rb");
// If file doesn't exist or can't open it then we can grab the latest file
if (f == NULL) {
die("Could not open myfile.txt file for reading.\n");
}
else {
char file_line [20];
int line_number = 0;
while (fgets (file_line, 20, f)) {
printf("Line %i: %s\n",line_number, file_line);

char *temp_string;
temp_string = strtok (file_line, " ");
if (temp_string != NULL) {
x_pos[line_number] = atoi(temp_string);
temp_string = strtok (NULL, " ");
if (temp_string != NULL) {
y_pos[line_number] = atoi(temp_string);
}
}
line_number++;
}
fclose(f);
}
}

which still prints the values as a check, this can be left out.

Writing to a file is also described above, which is useful for a highscore, eventually.

Writing in the example went well, but for the fact that the integers were written without a space, so the lines glued together.

This was solved adding:
char end_string[2] = { 0x0D, 0x0A};
fputs (end_string ,f);

so the function becomes:

void writeFile()
{

FILE *f = fopen ("myScorefile.txt", "wb");

int line_number = 5;

if (f == NULL) {
die("Could not open myScorefile.txt file for writing.\n");
}
else {
int x;
for (x = 0; x < line_number; x++) {
char temp_string[20];
sprintf(temp_string, "%i %i", x_pos[x], y_pos[x]);
fputs (temp_string ,f);
char end_string[2] = { 0x0D, 0x0A};
fputs (end_string ,f);
}
fclose(f);
}
}