在文件中写入/读取int数组的问题(c)

时间:2016-06-03 11:31:40

标签: c arrays file fwrite fread

我试图从一个文件,一堆整数,两个2d数组和两个1d数组中读取数据,整数读得很好,但是数组似乎读错了数据,我是不确定问题出在哪里:写作,阅读或内存分配。我没有收到编译器错误或崩溃,但我找不到问题。如果你能指出的话,我会对它进行说明。

void save(int found, int q, int a, int b, int dir,int **board,int **x_board, int n_players, int *p_ships, int *e_ships,int n_ships, int hor, int ver)
{
    int data[]={found,q,a,b,dir,p_ship_count,e_ship_count,n_players,n_ships,hor,ver};
    FILE *sfp;
    if((sfp = fopen("savegame","w"))==NULL)
            {
                 printf("Failed to open file");
                 exit(0);
            }
    fwrite(data,sizeof(int),sizeof(data),sfp);
    fwrite(p_ships,sizeof(int),sizeof(p_ships),sfp);
    fwrite(e_ships,sizeof(int),sizeof(e_ships),sfp);
    fwrite(board,sizeof(int),sizeof(board),sfp);
    fwrite(x_board,sizeof(int),sizeof(x_board),sfp);
    fclose(sfp);
}

int main()
{
...
int **a_board;
int **b_board;
int *p_ships;
int *e_ships;
...
            FILE *rfp;
            if((rfp = fopen("savegame","r"))==NULL)
            {
                 printf("Failed to open file");
                 exit(0);
            }
            else
            {
                fread(&found, sizeof(int), 1, rfp);
                fread(&q, sizeof(int), 1, rfp);
                fread(&a, sizeof(int), 1, rfp);
                fread(&b, sizeof(int), 1, rfp);
                fread(&dir, sizeof(int), 1, rfp);
                fread(&p_ship_count, sizeof(int), 1, rfp);
                fread(&e_ship_count, sizeof(int), 1, rfp);
                fread(&n_players, sizeof(int), 1, rfp);
                fread(&n_ships, sizeof(int), 1, rfp);
                fread(&hor, sizeof(int), 1, rfp);
                fread(&ver, sizeof(int), 1, rfp);

                p_ships=(int*)calloc(4*n_ships,sizeof(int));
                e_ships=(int*)calloc(4*n_ships,sizeof(int));
                fread(p_ships,sizeof(int),n_ships*4,rfp);
                fread(e_ships,sizeof(int),n_ships*4,rfp);

                a_board = (int**)calloc(hor+2,sizeof(int*));
                for(i=0;i<hor+2;++i)
                {
                    a_board[i]=(int*)calloc(ver+2,sizeof(int));
                }
                b_board = (int**)calloc(hor+2,sizeof(int*));
                for(i=0;i<hor+2;++i)
                {
                    b_board[i]=(int*)calloc(ver+2,sizeof(int));
                }
                if(n_players==1 || n_players==0)
                {
                    fread(*b_board,sizeof(int),(hor+2)*(ver+2),rfp);
                    fread(*a_board,sizeof(int),(hor+2)*(ver+2),rfp);
                }
                if(n_players==2)
                {
                    fread(*a_board,sizeof(int),(hor+2)*(ver+2),rfp);
                    fread(*b_board,sizeof(int),(hor+2)*(ver+2),rfp);
                }

                fclose(rfp);
            }

0 个答案:

没有答案