0

I am trying to adapt a matlab program to C, my problem is in the fwrite and fread function. On matlab I have:

fid = fopen ('sweep_100_3400.pcm','rb');
s = fread (fid, 'int16');

My doubt is, in C there are two more parameters in fread and fwrite function.

fread(void*, size_t, size_t, FILE*);
fwrite(const void*, size_t, size_t, FILE*);

In my C code I have:

arq = fopen("C:\\Users\\iago_\\Desktop\\MediaMovel\\sweep_100_3400.pcm", "rb");
fread(x, sizeof(double), itera, arq);
fclose(arq);

x is the vector where the data of my file will be saved.
sizeof(double) is the length of the data (I've declared all double)
arq is the pointer to the file.

The third parameter is a size_t, to adapt my matlab program, in this parameter should I use the media length or the vector size?

(I am encoding a moving average, the media length is informed by the user and the vector size is the length of my input file).

For the fwrite function I have the same doubt about the parameters.

arq=fopen("C:\\Users\\iago_\\Desktop\\MediaMovel\\saida_medial_movel_c.pcm", "wb");
fwrite(saida, sizeof(double), itera, arq);
fclose(arq); 
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Mutante
  • 278
  • 5
  • 18
  • 3
    The `size` and `count` arguments for `fread`, when multiplied, must be no larger than the receiving buffer size. A read of the man page will help you. Also, the return value from `fread` is significant, since the requested amount of data may not have been available. – Weather Vane Aug 22 '16 at 18:29
  • Post the definition of `saida` and how the value of `itera` is derived to better present the question. – chux - Reinstate Monica Aug 22 '16 at 19:14
  • Your aim is unclear, but if you are trying to write the data you read from one file with `fread` to another with `fwrite`, then the `count` argument for `fwrite` must be the return value from `fread` - the number of elements of size `size` that were read. – Weather Vane Aug 22 '16 at 19:21

1 Answers1

0

fread() parameters are

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

where nmemb is multiple of size function of read. So second parameter should be sizeof your vector and third should number of vectors you want to read from file pointer. Also there is but of confusion about matlab fread call. second param in matlab fread call is int16 which is 2 bytes, but in c fread call you have passed second param as sizeof(double) which is 8 bytes.

nrj_s
  • 19
  • 2
  • `sizeof(double)` is not guaranteed to be 8 bytes. Can be 1, 2, etc., depending on `CHAR_BIT` and the memory required for a `double`. Similar for `int16`: it can be `1` or `2`. – too honest for this site Aug 22 '16 at 19:21
  • I solved the problem using short type in my x vector instead double, with that works. – Mutante Aug 22 '16 at 19:29