Page 1 of 1

Can't write data / text to a file

Posted: Wed Jan 25, 2012 2:37 pm
by naid00
Hi there,

I recently started programming for my NDS. Totally new to the whole NDS programming stuff I ran into the following problem on my first program already: I can't get writing a file to my micro SD to work... I am using a R4i card with my NDS Lite and a 4 GB SDHC micro SD.

Code: Select all

#include <nds.h>
#include <fat.h>
#include <stdio.h>

void pause()
{
    // Wait for redraw of the display
    swiWaitForVBlank();
    
    // Tell the user what to do and wait
    iprintf("Press START to continue\n");
    do
    {
        scanKeys();
    } while (!(keysDown() & KEY_START));
    return;
}

int main(int argc, char **argv)
{
    consoleDemoInit();
    iprintf("Initialize libfat...\n");
    if (!fatInitDefault())
    {
        iprintf("Could not initialize libfat!\n");
        pause();
        return 0;
    }
    
    iprintf("Begin write...\n");
    pause();
    FILE *fp = fopen("/text.txt", "w");
    if(fp == NULL)
    {
        iprintf("Writing /text.txt: Error!\n");
        pause();
        return 0;
    }
    else
    {
        iprintf("Write something to /text.txt\n");
        int test = fprintf(fp, "Test\n");
        fclose(fp);
        if (test <= 0)
        {
            iprintf("Didn't work... BUT WHY???\n");
        }
        else
        {
            iprintf("Number of chars: %d\n", test);
        }
    }
    pause();
    return 0;
}
When I excecute the program on my NSD no error occurs. Even the number of bytes written to the file is returned... But when I mount the SD card on my laptop (Windows 7) I have the following phenomena: Sometimes the file is written but without any content. Sometimes the file is not even written. If it's written I can't delete it. As soon as I excecute the tool to restore filesystem errors the file disappears.

I really can't explain it... Maybe you have an idea?

MfG naid00

Re: Can't write data / text to a file

Posted: Thu Jan 26, 2012 8:40 pm
by elhobbs
you need to close the the file when you are done for it to completely flush to disk

Code: Select all

fclose(fp);

Re: Can't write data / text to a file

Posted: Thu Jan 26, 2012 11:13 pm
by naid00
Thank you for the fast answer elhobbs. I don't understand that though because I'm quite certain that I do close the file. The line is inside the else branch of my check on whether or not the file even could be created. Am I missing something there?

Re: Can't write data / text to a file

Posted: Wed Feb 01, 2012 1:19 pm
by naid00
Hm... maybe the problem is a hardware issue... Could anyone try to excecute the program on his NDS and tell me, if it works for him / her? If it does or does'nt i would like to know the hardware you're using (nds, slot1 or slot2 card model etc.). This would help me a lot.