I have piece of code which HAS to use the ANSI file functions.
I have a text file which stores 2 values: Address and Data. Its something like :
1 233
48 5.8
I want to extract these values from file and use them.
Here is how my code looks:
Code:
int main()
{
char * lbuf = new char(8); // To store add n data
int lreadBytes = 0;
long lAddress= 0;
double lData = 0;
FILE *pFile = fopen ("c:\\testprog1.txt","r");
if (pFile != NULL)
{
do{
// Read Address
lreadBytes = fread(lbuf,1 ,4, pFile); // where pfile is file pointer, Read 4 bytes for long
if(*lbuf == ' '|| *lbuf== '\t' || *lbuf == '\n')
{
continue;
}
// Convert char * to long
lAddress= atol(lbuf);
cout<< lAddress;
// Read Data corresponding to Address
lreadBytes = fread(lbuf,1 ,8, pFile);// Read 8 bytes for double
while(lreadBytes!= 0)
{
if(*lbuf == ' '|| *lbuf== '\t' || *lbuf == '\n')
{
continue;
}
// Convert data from char* to double
lData = atof(lbuf);
cout<<lData<<std::endl;
break; // Start reading next address
};
}while(lreadBytes!= 0); // Keep reading till all the bytes are read.
}
return 0;
}
Assume that long takes 4 bytes and double takes 8 bytes. But this code doesnt work.
Can this code be written in more optimized manner?
Thanks and Regards,
Shal