Hello.
I am trying to save some data to a txt file by using fprintf but for some reason the files I get are empty. The program creates the files fine, but for some reason it does not write anything to them.
It has worked before, but I had to make some changes to my program when this problem occurred. I have tried to find the problem for many hours now, but with no result.
I even tried using fopen_s instead of the normal fopen, but with no improvements.
Any help or suggestions will be greatly appreciated.
Here's the code of one of my header files (I have isolated the file from calling other functions for debug (you never know) by using comments //:
Code:
#include <stdio.h>
handleBoard(int param, int dimY, int dimX, int X, int Y, int totalMines)
{
int i, j, a, b, count = 0;
char** minesArray;
FILE *MinesFile, *DisplayFile;
MinesFile = fopen("MinesFile.txt","w+");
DisplayFile = fopen("DisplayFile.txt","w+");
// ALLOCATING A TWO-DIMENTIONAL DYNAMIC ARRAY FOR BOARD
minesArray = (char**)malloc(dimX*sizeof(char*));
for (i = 0; i < dimX; i++)
{
minesArray[i] = (char*)malloc(dimY * sizeof(char));
}
if (param == 0)
{
// SETTING ALL TILES TO STATUS 0 (CLOSED TILE ,NO MINE), EXCEPT FOR TILE AT X,Y WHICH GETS STATUS 2 (OPEN TILE, NO MINE)
for (i=0;i<dimX;i++)
{
for (j=0;j<dimY;j++)
{
if ((i == X) && (j == Y))
{
minesArray[i][j] = '2';
}
else
{
minesArray[i][j] = '0';
}
}
}
// PLANTING MINES AT RANDOM TILES WHILE ASSURING THAT NO MINE IS PLANTED AT X,Y
for (i=0;i<totalMines;i++)
{
a = rand() % dimX;
b = rand() % dimY;
if (minesArray[a][b] == '2')
{
i--;
}
else if (minesArray[a][b] == '1')
{
i--;
}
else if (minesArray[a][b] == '0')
{
minesArray[a][b] = '1';
}
else
{
printf("ERROR AT RAND()");
}
}
// SAVING DISPLAY- AND MINES DATA TO FILE
for (i=0;i<dimX;i++)
{
for (j=0;j<dimY;j++)
{
fprintf(MinesFile,"1");
if ((minesArray[i][j] == '0') || (minesArray[i][j] == '1'))
{
fprintf(DisplayFile,"c");
}
else if (minesArray[i][j] == '2')
{
fprintf(DisplayFile,".");
}
}
}
fclose(MinesFile);
fclose(DisplayFile);
}
else if (param == 1)
{
// LOADING DATA FROM FILE TO MEMORY
for (i = 0; i < dimX; i++)
{
for (j = 0; j < dimY; j++)
{
minesArray[i][j] = fgetc(MinesFile);
}
}
// CHECKING IF SELECTED TILE HAS NEIGHBOURING MINES
if (minesArray[X][Y] = '0')
{
//count = check4Neighbours(dimY, dimX, X, Y);
}
// IF IT HAS 1 OR MORE NEIGHBOURING MINES...
if (count > 0)
{
minesArray[X][Y] = (char)count;
// SAVING DATA TO FILE
for (i=0;i<dimX;i++)
{
for (j=0;j<dimY;j++)
{
fprintf(MinesFile,"%c",minesArray[i][j]);
}
}
fclose(MinesFile);
fclose(DisplayFile);
}
}
}