我正在编写一组函数以编写二进制文件,然后读取它并打印内容。结构必须是 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
游戏已经是一个指针struct score
。你需要
fwrite(game ,sizeof(struct score) ,1 , fp);//write to file
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句