Avoid damage to SD card in ansi C

I am currently working on an embedded Linux device for logging data. The Linux device is connected to CANbus and writes traffic to the SD card.

From time to time, the SD card is corrupted and mounted read-only. This behavior should be avoided.

FAT file system (SD card must remain readable by Windows systems).

The attached device may fail at any time, so I need a safe way to write to the SD card from my C program.

Since I'm really not in C, I rely on a program called "candump", which basically prints candessages to stdout in this format:

<0x006> [8] 77 00 00 00 00 00 00 00

My C program basically opens the candump program, reads from stdout, adds a timestamp, and removes unnecessary characters:

1345836055.520 6 7700000000000000


while(running)
{
    if (filename != NULL)
    {
        fp_log = fopen(filename, "a");
        if (!fp_log) 
        {
            perror("fopen");
            exit (EXIT_FAILURE);
        }  
    }  

    fgets(line, sizeof(line)-1, fp);

    /* reset the row_values so they are always correctly initialized */
    row_identifier = 0;

    if (strchr(line,'<') != NULL)
    {
        /* creating a buffer char to store values for casting char to int*/
        buffer_ident[0] = line[4];
        buffer_ident[1] = line[5];

        /* cast buffer e.g. {'1','0','\0'} to int: 10 */
        row_identifier = strtol(buffer_ident,NULL,10);

        /* heartbeat of the CANBUS PLC */
        if(row_identifier == 80)
        {
            /* return pong on identifier 81 to the PLC */
            //system("cansend can0 -i 81 1 > /dev/null");
        }
        else
        {
            gettimeofday(&tv,NULL);
            fprintf(fp_log,"%d.%03d ", tv.tv_sec, tv.tv_usec/1000);
            fprintf(fp_log,"%d ",row_identifier);

            /* rowlenght > 11 = data part is not empty */
            row_lenght = strlen(line);
            if (row_lenght>11)
            {
                int i=0;
                for (i=11;i<row_lenght;i++)
                    /* remove spaces between the data to save space and copy data into new array */
                    if (isspace(line[i]) == 0)
                        fprintf(fp_log,"%c",line[i]);
            fprintf(fp_log,"\n");   
            }
        }
    }
    fclose(fp_log);

}

, SD-.

ext3 .

+5
2

, , , FAT. J-16 SDiZ, , sync, .

, (, Ext3 NTFS. , , - fsck , rw , .

+1

, ? FILE *; .

, , - .

, , , ?

0

All Articles