I'm currently using CodeBlocks to try read double type data from a file and save it into an array, which so far I had success doing so. The issue is that when I try to save the data into an array, it print returns something else.
There is allocation memory for the array, and the code seems to be "ok". but it does not works as planned.
This is the code that I'm using.
ReadFile:
-9.9
-8.8
-7.7
-6.6
-5.5
-4.4
-3.3
-2.2
-1.1
0.0
1.1
2.2
3.3
4.4
5.5
6.6
7.7
8.8
9.9
10.10
C - Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0; //Array Size
int j; //Loop index
double* allMags; //Memory Allocation Array; Set Later
//START SECTION OF CODE TO ACCESS DOCUMENT FILE
FILE* ReadFile = NULL; //File Pointer
double FileNumber; //Data Value Read From File "ReadFile"
//OPEN FILE
printf("Opening File: ReadFile.txt\n");
ReadFile = fopen("ReadFile.txt", "r");
//If file fails to open
if (ReadFile == NULL)
{
printf("File could not be opened: 'ReadFile.txt'\n");
return -1; // -1 indicates Error.
}
//END SECTION OF CODE TO ACCESS DOCUMENT FILE
//START READ DATA AND STORE ARRAY SIZE
printf("Reading and printing numbers.\n");
for (i = i + 1; !feof(ReadFile); i++)
{
fscanf(ReadFile, "%lf", &FileNumber);
printf("Entry #%d || Read: %.2lf\n", i, FileNumber);
}
fclose(ReadFile); //End File for this instance
printf("\nArray Size: %d\n", i);
//END READ DATA AND STORE ARRAY SIZE
//START MEMORY ALLOCATION
allMags = (double*)malloc(sizeof(int)*i);
if (allMags == NULL)
{
printf("Closing File: ReadFile.txt\n");
fclose(ReadFile); //Done with File, close it
printf("allMags is NULL\n");
return -1;
}
//END MEMORY ALLOCATION
//START SCAN AND PRINT FROM ARRAY -- allMags
while (j <= i)
{
fscanf(ReadFile, "%lf", &(allMags[j-1]));
j = j + 1;
}
fclose(ReadFile); //Close File
printf("\nSaved Data:\n");
printf("\n");
j = 1;
while (j < i)
{
printf("Index: %d || Saved Read: %.2f\n", j, allMags[j]);
j++;
}
return 0; //KILL
}
As for the execution of the program, this is what I'm currently getting (Still don't quite figure out what is wrong).
This is What the console application output looks like