I am trying to write to a dat file that contains a header on how many entries there are as well as the entries themselves. Below is the file writing code:
As I read from the debugger, I'm getting something like the following that I'm assuming gets written to the file attached as arraywritten.txtCode:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> int main() { float slavepos[] = {.083, .21, .072, 0, 0, 0}; float delta = -0.001; int numslavepos = 100; float *slaveposwrite = (float*) malloc(100*6*sizeof(float)); char *FileName = "NeedleBasePos.dat"; FILE *fid; fid = fopen(FileName, "w"); fwrite(&numslavepos, sizeof(int), 1, fid); for (int i = 0; i < 100; i++) { memcpy(&slaveposwrite[6*i], &slavepos[0], 6*sizeof(float)); slavepos[1] += delta; } fwrite(slaveposwrite, sizeof(float), 6*100, fid); fclose(fid); free((void*) slaveposwrite); return 0; }
However, when I try to read the file in another code, while I'm reading the header properly in terms of the amount of entries, I am having trouble reading the entries properly. Below is my code for reading the file, and I have attached the garbage that I have read in arrayread.txt:
I don't know what possibly could cause me not being able to read (or write) the values properly. Any suggestions would be much appreciated.Code:void SPHandleError(int i) { char errormsg[200]; switch(i) { case 1: sprintf(errormsg, "Error opening file NeedleBasePos.dat !"); break; case 2: sprintf(errormsg, "Input file has an incompatible data structure\n"); break; default: sprintf(errormsg, "An unhandled error has occured !!"); } //if (MessageBox(NULL, errormsg, "Unrecoverable Error - Closing application", MB_ICONERROR)) exit(-1); } // Reading the needle trajectory from a text file // STATUS UPDATED: SlavePos void SlavePosFromFile( char *fname, slavepos_struct *needletippos ) { #define SPHEADERSIZE 1 FILE *spfile; int Sizes[SPHEADERSIZE], *Sizesptr = Sizes, pos; if( (spfile = fopen(fname, "rb")) == NULL) { SPHandleError(1); } else { printf("Bytes read for Needle Position trajectory from file '%s':\n", fname); } printf("NeedleBasePos.dat size = %d\n", fread(Sizes, sizeof(int), SPHEADERSIZE, spfile)); needletippos->entries = *(Sizesptr++); needletippos->SlavePos = (float*) calloc(SLAVEPOSELEMENTS*needletippos->entries, sizeof(float)); printf("SlavePos = %d\n", fread(needletippos->SlavePos, sizeof(float), SLAVEPOSELEMENTS*needletippos->entries, spfile)); // Check to see if more data is left in the file pos = ftell(spfile); fseek(spfile, 0, SEEK_END); if (ftell(spfile) != pos) SPHandleError(2); fclose(spfile); printf("Parameter file '%s' is read successfully.\n", fname); }



LinkBack URL
About LinkBacks


