nicolas - 3 months ago 13

C Question

I am writing 3200 floats like so:

`float fft[3200] = {0};`

get_fft_frame(dev, fft, 3200); // rf sensor

int written = write(sd, fft, sizeof(fft));

and reading then like this:

`float *fft = new float[3200];`

int inRead = 0;

while (inRead < (3200*4)) {

//sleep(1);

int bytesRead = read(sd, fft + inRead, (3200*4) - inRead);

inRead += bytesRead;

}

All the data is written in 1 write but it takes two read calls to get all the data. The first read returns 11584 and the second returns 1216.

The problem is that the second read call just reads zeros. However if I uncomment the sleep call, it reads all the correct data.

Is there a better way to get the data without sleeping?

Answer

You're mixing up your offsets. `inRead`

is measured in bytes, but when you add it to `fft`

it is multiplied by `sizeof float`

by the rules of pointer arithmetic. The offset expression in the `read()`

call should be

```
((char*)fft)+inRead
```

Source (Stackoverflow)

Comments