将结构写入二进制文件,从文件中读取,存储在缓冲区中,打印缓冲区

时间:2016-12-07 10:06:13

标签: c file binaryfiles

我正在尝试将结构写入二进制文件,标点符号将作为insertInFile函数中的参数接收,(使用raspberryPi,并存储时间反应的值与开关)。然后我想从文件中读取并将值存储在堆上,最后读取我动态存储的值。我遇到了这个问题,因为它无法正常读取或无法写入二进制文件。

typedef enum dificulty {
    EASY, MEDIUM, HARD
} Dificulty;
typedef struct player {
    char nickname[MAXSIZE];
    enum dificulty Dificulty;
    float pontuacion;
} Player;

#define LED_CYCLES 5
#define MAX_PLAYERS 2

int insertInFile(float const *const timeReceived, unsigned short *level, char *playerName) {
    Player players[MAX_PLAYERS];
    int count = 0, i;
    FILE *fplayers;

    //check if file can be opened
    if ((fplayers = fopen("game.bin", "wb")) == NULL) {
        fputs("Erro ao abrir ficheiro\n", stderror);
        return (-1);
    }
    //go to the beginning of the file
    rewind(fplayers);

    //cycle that allows to save int the bin file the struct "Player"
    for (i = 0; i < count; i++) {
        Player[i].pontuacion = &timeReceived[count];
        Player[i].Dificulty = &level;
        Player[i].nickname = &playerName;
        fwrite(&players, sizeof (Player), count, fplayers);
    }

    //close the bin file
    fclose(fplayers);

    return 0;
}

void obtainFromFile() {
    Player players;
    int count = 0;
    FILE *fplayers;
    size_t size;
    unsigned char *buffer;
    int i;

    //open file
    fp = fopen("game.bin", "rb");
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);        // calculate the size needed
    fseek(fp, 0, SEEK_SET);
    buffer = (unsigned char *)malloc(size);

    if (fplayers == NULL) {  // check some error if file == empty
        printf("Error\n", stderr);
        return (-1);
    } else
    if (fread(&buffer, sizeof (*buffer), size, fp) != size) // if count of read bytes != calculated size of .bin file -> ERROR
        printf("Error\n", stderr);
        return (-1);
    } else {
        for (i = 0; i < size; i++) {
            printf("%02x", buffer[i]);
        }
    }
    fclose(fp);
    free(buffer);
}

1 个答案:

答案 0 :(得分:1)

insertInFile()中,对结构使用存在误解。写Player.pontuacion是不对的。

  

要在struct Player players[MAX_PLAYERS];数组中指定值,请使用players[i].Dificulty = (Dificulty)level

//cicle that allows to save int the bin file the struct "Player"
for (i = 0; i < count; i++) {
    players[i].pontuacion = timeReceived[count];
    players[i].Dificulty = (Dificulty)(level[count]);
    strncpy(players[i].nickname,playerName,MAXSIZE-1);
    players[i].nickname[MAXSIZE]='\0';
}
// write count players
fwrite(&(players[0]), sizeof (Player), count, fplayers);

而不是:

for (i = 0; i < count; i++) {
    Player.pontuacion = &timeReceived[count];
    Player.Dificulty = &level;
    Player.nickname = &playerName;
    fwrite(&players, sizeof (Player), count, fplayers);
}