Я пишу набор функций, чтобы написать двоичный файл, а затем прочитать его и распечатать содержимое. Структура должна быть 1 байт, и каждый член должен хранить число от 0 до 15 - всего 8 бит) в каждом (жестко запрограммировано мной в main()). Проблема, с которой я сталкиваюсь, заключается в том, что моя функция записи не сохраняет правильные числа в файле, который она создает, как те, которые я жестко запрограммировал в структуру. Я пытался понять это, и я не уверен, в чем проблема... У меня есть другая программа, которая отлично работает с очень похожей целью. Пожалуйста, посмотрите мой код ниже и результат, который я получаю. Также у меня есть несколько распечаток, сделанных при попытке устранить неполадки.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Purpose:
*/
struct score{
//max 15 values for each
//4 bits for player1 and 4 for player2
unsigned char player1:4;
unsigned char player2:4;
};
void printGG(struct score* game){
printf("%hhu:%hhu\n", game->player1 , game->player2);
}
int writeGG(struct score* game, char * fileName){
FILE *fp;
if (!(fp=fopen(fileName,"wb"))){
return 1;//file open error
}
//print to test the game pointer
printf("WRITEGG() : player1: %d, player2: %d\n", game->player1, game->player2 );
fwrite(&game ,sizeof(struct score) ,1 , fp);//write to file
// check if fwrite failed
if (fp == NULL){
fprintf(stderr,"fwrite failed on %s\n",fileName);
exit(EXIT_FAILURE);//can't write
}
fclose(fp);
return 0;//normal termination
}
//reads provided .bin file and populates a score struct, then prints it.
int readGG(char *fileName)
{
FILE *fp;
if (!(fp=fopen(fileName,"rb"))){
fprintf(stderr,"failed to open %s\n",fileName);
exit(EXIT_FAILURE);//can't open
}
struct score s;
if (fread(&s ,sizeof(struct score) ,1 , fp)!=1) return 2;//read error
printf("readGG() : player1: %d, player2: %d\n", s.player1, s.player2 );
fclose(fp);
printf("%hhu:%hhu\n",s.player1,s.player2);
return 0;//normal termination
}
int main()
{
//create the score struct
struct score scores;
//hard code the scores
scores.player1 = 10;
scores.player2 = 1;
printf(" player 1 has: %d\n",scores.player1);
printf(" player 2 has: %d\n",scores.player2);
//print the score in the format score:score
printGG(&scores);
//write to bin file
writeGG(&scores, "Score.bin");
//read file
readGG("Score.bin");
return 0;
}
Я чувствую, что это может быть просто небольшая ошибка, которую я пропускаю, но я просто не вижу ее.
//Output for the main() when ran:
player 1 has: 10
player 2 has: 1
10:1
WRITEGG() : player1: 10, player2: 1
15:1
//here the .bin file contains just the letters 1F...which is 15 and 1,
//not 10 and 1 which i have entered.
Вы пишете адрес struct score *game
fwrite(&game ,sizeof(struct score) ,1 , fp);//write to file
game уже является указателем на struct score
. Тебе нужно
fwrite(game ,sizeof(struct score) ,1 , fp);//write to file
большое спасибо! да, это имеет смысл сейчас.