Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem with buffer in fread and fwite functions

Status
Not open for further replies.

hamsha

Programmer
Jan 3, 2006
1
IT
Hi everyone
I have some problem with fread and fwrite in VS2005 beta2
I have the following code, in it i generate a buffer and after assigning some values to it , i write it to a file , then i try to read it back to a new buffer which is not successful.
for variable bigVal=100 i get "k=100" for writing but for reading i get "k=77" , i would be pleased if someone can help me.

#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include <stdio.h>

typedef double dtype;


int _tmain(int argc, _TCHAR* argv[])
{

dtype *b;
int i,j,k;
int bigVal;
char filename[]="c:\\temp.data";
FILE *fp;

bigVal=100;
b=(dtype*) malloc(bigVal * sizeof(dtype));

for(i=0 ; i<bigVal ; i++)
{
b=(i+1)/double(rand());
printf("b[%i]=%3.3g ",i,b);
}


if( (fp=fopen(filename,"w")) == NULL)
{
printf("Error in writing file %s \n",filename);
}
else
{
k=fwrite(b,sizeof(dtype),bigVal,fp);
printf("\n%i items wrote to file \n",k); // I get k=100 on my pc
fflush(fp);
fclose(fp);
}

free(b);

//tring to read the content of file
b=(dtype*) malloc(bigVal * sizeof(dtype));
if( (fp=fopen(filename,"r")) == NULL)
{
printf("Error in reading file %s \n",filename);
}
else
{
k=fread(b,sizeof(dtype),bigVal,fp);
printf("\n%i items read from file \n",k);// I get k=77 on my pc
fclose(fp);
}
for(i=0 ; i<bigVal ; i++)
{
printf("b[%i]=%3.3g ",i,b);
// here on my pc from start to b[76] are ok but b[77] to end are Not ok
}

free(b);
return 0;
}
 
> b=(dtype*) malloc(bigVal * sizeof(dtype));
Are you intending this to be a C or C++ program?
If it's C, then there's no need to cast malloc.
If it's C++, then you should be using new/delete for memory allocation.

> if( (fp=fopen(filename,"r")) == NULL)
Try it with "rb" and "wb" when opening the file.

Please remember to use [code][/code] tags when posting code.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top