strange outputs using fread
Hi all,
This is my first post on this site. I am taking c programming at college and plan on continuing with more advanced program classes.
I am writing a program that reads from a binary file (if one exists). If not the user can create and write data to one. On the next program run, fread will read from the file and populate an array before going to the fwrite functions. I put a bunch of printf's under the fread so I could test the results of the array. I also have some code commented out that I was toying with, trying to get this to work.
This is the output that I am getting from my printf tests
20
40
-858993460
60
-858993460
-858993460
80
-858993460
-858993460
I should be getting: 20,40,60,80,100,120,140,160,180,200
Here is my code, Is it the fread that is screwing things up? Or is it how the data is written (fwrite)? If it were a text file, I could at least eliminate one option.
Thanks in advance,
Michael
Code:
void loadArray() {
int userInput[MAXSIZE] = {0};
int temp = 0;
int count = 0;
int counter=0;
FILE *binaryPointer;
binaryPointer = fopen("binaryFile.bin", "rb");
if(binaryPointer) {
while(!feof(binaryPointer)) {
fread(&count, sizeof(int), 1, binaryPointer);
userInput[counter] = count;
counter++;
}
fclose(binaryPointer);
printf("%d\n", userInput[0]);
printf("%d\n", userInput[1]);
printf("%d\n", userInput[2]);
printf("%d\n", userInput[3]);
printf("%d\n", userInput[4]);
printf("%d\n", userInput[5]);
printf("%d\n", userInput[6]);
printf("%d\n", userInput[7]);
printf("%d\n", userInput[8]);
pause;
}
else {
printf("The file does not exist, press any key to create one and write data to it\n");
pause;
}
binaryPointer = fopen("binaryFile.bin", "ab+");
while (temp != -999){
printf("Please enter a number to be stored in the array. Enter -999 to quit - ");
scanf("%d", &temp);
userInput[counter] = temp;
counter++;
count++;
fwrite(&temp, sizeof(int), count, binaryPointer);
}
fclose(binaryPointer);
}