数据库混淆

时间:2016-12-24 18:38:26

标签: c

我的代码执行中有一件奇怪的事情 除了player_count的值之外,每件事都可以。当我从文件中再次读取数据时,它仍然= 0,尽管名称和电子邮件已正确更新.. !! 为什么player_count仍然等于0 ??????

这是代码:

#define MAX_DATA 128
#define STRLEN   101
#define FILENAME "C:\\Users\\ahmed\\Desktop\\C codes\\new_game\\data_base.dat"
typedef struct
{
 char name[STRLEN] ;
 char email[STRLEN] ;
 int  score ;
 int id ;
 int Set ;
}  player_t ;

 typedef struct
 {
  player_t  player[MAX_DATA] ;
  int player_count ;
 }DataBase ;

typedef struct
{
  DataBase db ;
  FILE *filename ;

}Connection ;

void Store_Player_Database( int score )
{

Connection *conn = Creat_Connection(FILENAME );
player_t *player = conn->db.player ;

Read_Database(conn) ;

int player_num = conn->db.player_count ;

printf("Your name : ") ;
get_str(player[player_num].name , STRLEN) ;
printf("Your e-mail : ") ;
get_str(player[player_num].email , STRLEN) ;
player[player_num].Set = 1 ;
player[player_num].score = score ;
conn->db.player_count++ ;
printf("count here = %d\n",conn->db.player_count) ;
Write_Database(conn) ;

}

Connection *Creat_Connection(const char *filename )
{
Connection *conn = calloc(1,sizeof(Connection)) ;
//check_mem(conn) ;

int i = 0;
for( i = 0 ; i< MAX_DATA ; i++)
    conn->db.player[i].id = i+1 ;

/// for update or read

    conn->filename = fopen(filename , "r+") ;
    //check(db->filename  , "File open failed !") ;

    return conn ;
}

int Read_Database(Connection *conn)
 {

int rc ;
if(conn)
{
    if(conn->filename)
    {

        DataBase *db = &conn->db ;
        rc=fread(db,sizeof(DataBase),1,conn->filename);  // load database from file .
        printf("count = %d\n" , db->player_count) ;printf("%s %s \n" , db->player[0].name  , db->player[0].email);
       /* if (rc != 1)
        {
            printf("Error load database from file\n") ;
            return -1 ;
        }*/

  }
}
return 1 ;
}


int Write_Database(Connection *conn)
{

int rc ;
if(conn)
  {
     if(conn->filename)
     {
          rewind(conn->filename) ;
          DataBase *db = &conn->db ;printf("%s %s count = %d \n" , db->player[0].name  , db->player[0].email , conn->db.player_count);
          rc = fwrite(db,sizeof(DataBase),1,conn->filename) ;
          if (rc != 1)
          {
            printf("Error load database from file\n") ;
            return -1 ;
          }
          fflush(conn->filename) ;

     }

}
return 1 ;
}

/*****************************/
int main(void)
{
  int score  = 5 ;

   /* any code here */

   Store_Player_Database(score) ;
   Store_Player_Database(score +1) ; // at that call i get name and mail correct but player_count still zero ??? why?! 

    return 0 ;
 }

1 个答案:

答案 0 :(得分:0)

当我在linux中尝试这个程序时,它正确运行
然后我终于找到了这个bug。 在Windows中,fread应该以二进制模式打开:

conn->filename = fopen(filename , "rb+") ; // use rb+ instead of r+ to open it in binary mode