1

This may sounds little odd or question may be a trivial one, but for most of my life I was programming in PHP (yeah, I know how it sounds). So when I switched to C++ there are things quite unfamilliar for me (cause of php habits).

So I'm loading wav header data using struct. Values are definded as uint8_t type:

typedef struct  WAV_HEADER
{
   uint8_t         RIFF[4];        // RIFF
   uint8_t         WAVE[4];        // WAVE
}

I have to compare them with four-letter strings for something like that:

if(wavHeader.RIFF[0] . wavHeader.RIFF[1] . wavHeader.RIFF[2] . wavHeader.RIFF[3] == 'RIFF')
{ do sth }

This should be easy check if loaded file is a Wave file (*.wav). Thanks for any help.

user3038744
  • 86
  • 1
  • 8
  • 3
    What you probably want is `if(memcmp(wavHeader.RIFF,"RIFF",4) == 0)` – πάντα ῥεῖ Jan 09 '16 at 12:03
  • Yeah, that works. Thank you. By the way, is there any other resolution, that includes not including memory.h? – user3038744 Jan 09 '16 at 12:06
  • 3
    Of course you can also do `if(wavHeader.RIFF[0] == 'R' && wavHeader.RIFF[1] == 'I' && wavHeader.RIFF[2] == 'F' && wavHeader.RIFF[3] == 'F')` – πάντα ῥεῖ Jan 09 '16 at 12:09
  • non-portable solution, needs `RIFF` to be properly aligned: `*(int*)RIFF == 'RIFF'` or `*(int*)RIFF == 'FFIR'` depending on endianness. To make it more portable: `*(int*)RIFF == 0x46464952` – phuclv Jan 09 '16 at 16:43

1 Answers1

4

Strings in C and C++ are null-terminated. RIFF and WAVE aren't technically C-style strings because there is no null terminator, so you can't just use a straightforward C/C++-style string compare like strcmp. There are however several ways you could compare them against the strings you want:

  • if (header.RIFF[0] == 'R' && header.RIFF[1] == 'I' && header.RIFF[2] == 'F' && header.RIFF[3] == 'F') { // .. }
  • if (strncmp((const char*)header.RIFF, "RIFF", 4) == 0) { // .. }
  • if (memcmp(header.RIFF, "RIFF", 4) == 0) { // .. }

I would personally use either strncmp or memcmp. They end up doing the same thing, but semantically strncmp is a string compare function which maybe makes the code clearer.

For strncmp see here. For memcmp see here.

Community
  • 1
  • 1
Sam
  • 3,320
  • 1
  • 17
  • 22
  • What error do you get, and what compiler are you using? You'll have to include `string.h` to use `strncmp`. – Sam Jan 09 '16 at 12:50
  • Oops, thanks, I updated my answer. You'll have to cast the `RIFF` member to a `const char*` to use `strncmp`. – Sam Jan 09 '16 at 12:53
  • 1
    I just meant that they aren't technically strings since they don't have any null terminator, but semantically you would probably think of them as strings. I added some text to mention that. Hopefully it's a bit clearer. – Sam Jan 09 '16 at 13:06
  • Yeah, I'd say that makes your logic a lot clearer, thanks. –  Jan 09 '16 at 13:23