Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 485
  • Last Modified:

Read from buffer not file

Hello,
in my old code I worked with fread to read from an little text file some settings. This I want now replace with reading from a buffer (char).  The original ocde is:
	int val;
	fread(&val, sizeof(int), 1, f); DBFFTSize  = val;
	fread(&val, sizeof(int), 1, f); DBNumFFTs  = val;
	fread(&val, sizeof(int), 1, f); DBNumBins  = val;
	fread(&val, sizeof(int), 1, f); DBFirstBin = val;
	fread(DBOrgBuf, sizeof(float), 16, f);
	fclose(f);

Open in new window

How to replace this while read from a char buffer.  I have a buffer that was filled before and that was initialized with:
char buff[100];
memset(buff,0,sizeof(buff));

Open in new window


Thanks,

Ingo
0
Ingo Foerster
Asked:
Ingo Foerster
  • 3
  • 2
1 Solution
 
jkrCommented:
In this case, 'read' might not be the right term. You'd just interpret the buffer's content differently, i.e.

struct FFTVals {

  int DBFFTSize;
  int DBNumFFTs;
  int DBNumBins;
  int DBFirstBin;
  float DBOrgBuf[16];
};

// ...

char buff[100];
memset(buff,0,sizeof(buff));

// ...

FFTVals* pVals = (FFTVals*) buff; // consider 'buff' as 'read'

// copy values - or just use them directly from 'pVals'
  int DBFFTSize = pVals->DBFFTSize;
  int DBNumFFTs = pVals->DBNumFFTs;
  int DBNumBins = pVals->DBNumBins;
  int DBFirstBin = pVals->DBFirstBin;
  // etc.

Open in new window

0
 
jkrCommented:
BTW, the above would as well work to read your file in one single call, e.g.

fread(buff, 4 * sizeof(int) + 16* sizeof(float), 1, f);

FFTVals* pVals = (FFTVals*) buff;

Open in new window

0
 
Ingo FoersterAuthor Commented:
ok, how to get the float to a existing float value:

existing:
float cinDBOrgBuf[16];
cinDBOrgBuf = pVals->DBOrgBuf; 

Open in new window


do not work.
0
 
jkrCommented:
That can be done like

float cinDBOrgBuf[16];
for (int i = 0; i < 16; ++i)
  cinDBOrgBuf[i] = pVals->DBOrgBuf[i]; 

Open in new window


or simply like

float cinDBOrgBuf[16];
memcpy(cinDBOrgBuf,pVals->DBOrgBuf,16 * sizeof(float)); 

Open in new window


But, as I wrote, there is no need to duplicate these values, you can use them directly from 'pVal'.
0
 
Ingo FoersterAuthor Commented:
Exact what I was looking for. Many thanks!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now