Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating files in C

Tags:

c

I need to validate load files for a game I'm making and I'm having troubles with it:

I just need to know if the first character is an int in some range, if the next one is an unsigned short int (checking the type and value of each character), and I couldn't find a function for this.

Also, I need to check if the n-th character is the last character in the file (return some error code if it is not).

The file is binary type.

How could I resolve this?

Thanks!

E:

This is my load file function:

Cod_Error load(Info * gameInfo)
{
    FILE * loadFile;
    unsigned short int dif;
    int i;


    randomizeSeed();

    gameInfo ->undo = FALSE;

    loadFile = fopen(gameInfo->fileArchivo, "rb");


    fread(&dif, sizeof(dif), 1, loadFile);

    gameInfo->size = sizeFromDif(dif);
    gameInfo->undoPossible = FALSE;

    gameInfo->board = newBoard(gameInfo->size);
    if(gameInfo->board == NULL)
        return ERROR_MEM;

    fread(&(gameInfo->score), sizeof(Score), 1, loadFile);

    fread(&(gameInfo->undos), sizeof(unsigned short int), 1, loadFile);

    for(i = 0; i < gameInfo->size; i++)
        fread(gameInfo->board[i], sizeof(Tile), gameInfo->size, loadFile);

    fclose(loadFile);

    return OK;
}
like image 299
YoTengoUnLCD Avatar asked Oct 30 '22 16:10

YoTengoUnLCD


1 Answers

Short Answer: You can't.

Long Answer:

In a binary file, there is no specification for what the binary data represents. That specification has to come from the developer of the program reading the file. For instance, lets take 2 bytes from an arbitrary file.

00101101 00110111

Now, what that is is entirely dependant on the program reading these bytes. You can try to read it as an int, and check if it makes sense (i.E is within a certain range) if interpreted as an int, and you can do the same for any other combination of binary data with any other data type. But you decidedly cannot tell what data type was used for writing it into the file, as now its just binary.

To quote @M.Oehm:

You can't read 4 bytes and say "Oh, they are a float".

You can say however,

"If I count these as a float, are they within a specified range I set?"

like image 171
Magisch Avatar answered Nov 15 '22 07:11

Magisch