PROS error writting to SD card

I am trying to write data to a file on the SD card (in the slot in the brain).

In opcontrol I there is:
FILE *file = fopen("/usd/dd.txt", "a+");
and in the main loop in opcontrol there is:

...
fputs("test\n", file);
pros::delay(10);

When I run the code it gives me a DATA ABORT EXECPTION on the brain.

Is the data abort exception because of fopen or the fputs. If it is from the fopen try with a instead of a+ if it is because the fputs check if the file is NULL. Also just a sanity check is the SD card actually plugged in?

3 Likes

“a” removes the error message, but the file is still blank when I remove it and plug it into the computer (after running the program).

You get a data abort exception when you try to reference invalid memory or dereference a null pointer. The documentation of fopen says that if opening the file fails, it will return NULL. Assuming the fopen failed, then giving fputs NULL will cause the program to crash (as it tries to use NULL as a memory location).

The proper way of handling a file pointer (so there is no crash) is this:

FILE *file = fopen("/usd/dd.txt", "a+");
if(file) {
  // success
  fputs("test\n", file);
} else {
  // failed
  printf("Failed to open\n");
}

However, I’m not sure why it’s not working. Try putting fclose at the bottom of the file, to force a buffer flush.

3 Likes

Thanks for the advice, I already have an fclose at the end of the file but its an infinite loop so it will never get there, do you think that’s the problem?

Lol, what’s the point of having an fclose if it is never reached. fclose causes the file buffer to flush, which may or may not happen automatically, depending on how fast you are writing and how much you are delaying before you terminate the program.

You can also try to use fflush.

2 Likes

Ok, it turns out it was the close command! I added a hotkey to break the loop and now it works, thanks!