Qt - Bytearray with empty entries? - c++

I'm working on a simple function which is able to return a int in Qt using information sent to a comport.
I'm using the QSerialPort class which returns a QBytearray.
The problem is i seem (on occasion) to get empty entries in the array that QSerialPort.readAll returns. This makes me unable to convert the bytearray to an int.
The basic functionality is: Ask for Arduino to send either temperature or humidity.
Qt code:
#include <QCoreApplication>
#include <QSerialPortInfo>
#include <QSerialPort>
#include <iostream>
#include <string>
#include <windows.h>
#include <math.h>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString comPort = "COM6";
QSerialPortInfo ArduinoInfo(comPort);
cout << "Manufacturer: " << ArduinoInfo.manufacturer().toStdString() << endl;
cout << "Product Identifier: " << ArduinoInfo.productIdentifier() << endl;
cout << "Vendor Identifier: " << ArduinoInfo.vendorIdentifier() << endl;
QSerialPort Arduino(ArduinoInfo);
Arduino.setBaudRate(QSerialPort::Baud9600);
Arduino.open(QSerialPort::ReadWrite);
Sleep(1000);
if(Arduino.isDataTerminalReady())
cout << "Great Sucess" << endl;
char sending = 'H';
cout << sending << endl;
Arduino.write(&sending, 1);
//int maxSize = Arduino.bytesAvailable();
while(!Arduino.waitForReadyRead()){}
Sleep(100);
QByteArray rawDataArry = Arduino.readAll();
cout << "Shit has been read." << endl;
// Form here on its just write functions, used for debug
cout << "rawData:" << endl;
for(int i=0; i < rawDataArry.size(); i++)
cout << "[" << i << "] "<< rawDataArry[i] << endl;
cout << "All data:" << endl;
for(char s:rawDataArry){
cout << s;
}
cout << endl;
cout << "Converted data:" << endl;
bool ok;
int returnVar = rawDataArry.toInt(&ok, 10);
cout << returnVar << endl;
cout << "Convertion Status:" << ok;
Arduino.close();
return a.exec();
}
The Arduino code is super simple.
#include <dht.h>
dht DHT;
#define PIN_7 7
void setup() {
Serial.begin(9600);
}
void loop()
{
String impString;
while(Serial.available() != 1);
impString = Serial.readString();
DHT.read11(PIN_7);
if(impString == "T")
{
int temp = DHT.temperature;
Serial.println(temp);
}
else if(impString == "H")
{
int humid = DHT.humidity;
Serial.println(humid);
}
emptyReceiveBuf();
delay(100);
}
void emptyReceiveBuf()
{
int x;
delay(200); // vent lige 200 ms paa at alt er kommet over
while (0 < Serial.available())
{
x = Serial.read();
}
}
Terminal monitor displays:

Looks like rawDataArry.size() is returning 4, so that means there ARE 4 bytes in the array. However, when you call rawDataArry[i] it returns a char. Not every char value can be represented as an ascii character. Which is why the last 2 bytes appear empty.
Instead you should try to convert each char to a value that shows the decimal/hex representation of the byte instead of the ascii representation.
Alternatively, you could convert those 4 bytes right to an int and be done with it:
//Big Endian
quint32 myValue(0);
for(int i=0; i<4; i++)
myValue = myValue + (quint8(rawDataArry.at(i)) << (3-i)*8);
//myValue should now have your integer value

I ended up using a member of QByteArray to clean up the widespaces in the array!
It looks something like this!
bool ok;
int returnVal;
do
{
Arduino.write(&imputChar, 1); // Arduino input Char
Arduino.waitForReadyRead();
QByteArray rawDataArry(Arduino.readAll()); // Empties buffer into rawDataArry
QByteArray dataArray(rawDataArry.simplified()); // Removes all widespaces!
returnVal = dataArray.toInt(&ok, 10); // Retuns ByteConvertion - &OK is true if convertion has completed - Widespaces will ruin the conversion
qDebug() << "Converted data:";
qDebug() << returnVal;
qDebug() << "Convertion Status:" << ok;
}while(ok != 1);
return(returnVal);

Related

How to declare function using reference?

I am making this program to check the alphabetic and numeric characters of a C-type string. I am using C-type strings because it is for an assignment, otherwise I would opt to use std::string.
How do I declare the function? In my case, I want str, SAlpha and SNum, to be stored in the function as s, alpha, num. That's why I am using references, but I don't understand how to declare it without giving me an error saying undefined.
I have been searching, but I am new to functions, and don't understand them quite well. That's why I'm asking.
Below is the code:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
void seperate(char (&s)[], char (&alpha)[], char (&num)[]);
int main() {
char str[100];
char SAlpha[100];
char SNum[100];
cout << "Insert a string: ";
cin.getline(str,100);
strcpy(SAlpha, str);
strcpy(SNum,str);
cout << "Alphabetic characters " << endl;
for (int i = 0; i < strlen(SAlpha); i++) {
if (isalpha(SAlpha[i])) {
cout << " " << SAlpha[i];
}
}
cout << endl;
cout << "Numeric characters " << endl;
for (int i = 0; i < strlen(SNum);i++) {
if (isdigit(SNum[i])) {
cout << " " << SNum[i];
}
}
seperate(str, SAlpha, SNum); //UNDEFINED FUNCTION
return 0;
}
You are getting an "undefined" error because you have only declared the seperate() function but have not implemented it yet, eg:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
// THIS IS JUST A DECLARATION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100]);
int main() {
char str[100];
char SAlpha[100];
char SNum[100];
cout << "Insert a string: ";
cin.getline(str,100);
strcpy(SAlpha, str);
strcpy(SNum,str);
cout << "Alphabetic characters " << endl;
for (int i = 0; i < strlen(SAlpha); i++) {
if (isalpha(SAlpha[i])) {
cout << " " << SAlpha[i];
}
}
cout << endl;
cout << "Numeric characters " << endl;
for (int i = 0; i < strlen(SNum);i++) {
if (isdigit(SNum[i])) {
cout << " " << SNum[i];
}
}
seperate(str, SAlpha, SNum); // <-- OK TO CALL SINCE THE FUNCTION IS DECLARED ABOVE...
return 0;
}
// ADD THIS DEFINITION!!!
void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100])
{
// do something here...
}

C++ Array values being altered at element 4 after throwing exception

The requirements for the program state that the try/catch must be placed in the main.cpp as below:
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
When it accesses the method:
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
It doesn't seem to matter which variation of throwing I use, my array gets destroyed afterward. It works fine if it stays within bounds, or I work it to not throw from the method (doing the error checking elsewhere), but the requirements state that it has to be that way, so I must be missing something. Full code below:
main.h:
#ifndef MAIN_H
#define MAIN_H
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER
***********************************/
#include <iostream> /* cout, endl */
#include "mylist.h"
#include <stdexcept>
#define LISTSIZE 10
using std::cout;
using std::endl;
int elementResult;
#endif /* MAIN_H */
main.cpp:
#include "main.h"
int main(int argc, char** argv) {
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER AND
* UNCOMMENT THINGS AS YOU COMPLETE
* THE FUNCTIONALITY OF YOUR LIST OBJECT
***********************************/
/* This will create a "list" of size LISTSIZE
* and initialize it to all zeros */
cout << "create and initialize mylist" << endl;
MyList mylist(LISTSIZE);
mylist.printArray();
cout << endl;
/* This will set the list to all 50 */
cout << "set mylist to all 50" << endl;
mylist.setArray(50);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers -2 to 4" << endl;
mylist.setRandom(-2,4);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers 4 to 4" << endl;
mylist.setRandom(4,4);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 1-100 values */
cout << "attempt to set to random numbers 1 to 100" << endl;
mylist.setRandom(1,100);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 500-1000 values */
cout << "attempt to set to random numbers 500 to 1000" << endl;
mylist.setRandom(1000,500);
mylist.printArray();
cout << endl;
/* These next two sets will succeed and set the 1st and last
* elements to 1000 and 2000 respectively */
if(mylist.setElement(1000, 0)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(2000, LISTSIZE-1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
/* These next two sets will fail and leave the array unmodified */
if(mylist.setElement(9999, -1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(9999, LISTSIZE)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
cout << "Testing new and/or modified code..." << endl << endl;
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
mylist.printArray();
cout << "attempting to get element 4000 using: int getElement(int);" << endl;
try{
cout << mylist.getElement(4000) << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
cout << endl;
cout << "printing the array element by element using: int getElement(int,int*);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
if(mylist.getElement(i, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
cout << "attempting to get element 4000 using: int getElement(int,int*);" << endl;
if(mylist.getElement(4000, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
return 0;
}
mylist.h:
#ifndef MYLIST_H
#define MYLIST_H
#include <iostream> /* cout, endl */
#include <stdlib.h> /* srand, rand, atoi */
#include <time.h> /* time */
#include <stdexcept>
// you can add libraries if you need them, but you shouldn't
// DO NOT MODIFY THESE DEFINES
#define RMIN 1
#define RMAX 10
#define DEFAULT_SIZE 10
using std::cout;
using std::endl;
class MyList {
public:
// DO NOT MODIFY THESES NEXT TWO
MyList(int); // constructor
~MyList(); // destructor
int getElement(int);
void setArray(int);
bool setElement(int, int);
void setRandom(int, int);
void printArray();
bool getElement(int, int*);
private:
// these are the only attributes allowed
// DO NOT ADD OR MODIFY THEM
int length;
int *array;
};
#endif //MYLIST_H
mylist.cpp:
#include "mylist.h"
// constructor
MyList::MyList(int size) {
srand(time(NULL)); // call only once!
if(size < 1){
size = DEFAULT_SIZE;
}
MyList::length = size;
MyList::array = new int(size);
setArray(0);
}
// destructor
MyList::~MyList() {
//delete[] MyList::array;
}
void MyList::printArray() {
cout << "[";
for (int i = 0; i < length; i++){
if (i == length - 1){
cout << array[i];
}else{
cout << array[i] << " ";
}
}
cout << "]" << endl;
}
void MyList::setArray(int setArrayTo){
for (int i = 0; i < length; i++){
MyList::array[i] = setArrayTo;
}
}
void MyList::setRandom(int numOne, int numTwo){
bool isValidRandom = true;
int randMin, randMax;
if((numOne < RMIN) || (numTwo < RMIN) || (numOne == numTwo)){ isValidRandom = false; }
if(isValidRandom == true){
if(numTwo < numOne){
randMin = numTwo;
randMax = numOne;
} else {
randMin = numOne;
randMax = numTwo;
}
} else {
randMin = RMIN;
randMax = RMAX;
}
for(int i = 0;i < length; i++){
MyList::array[i] = rand() % randMax + randMin;
}
}
bool MyList::setElement(int passedValue, int arrayIndex){
bool isInRange = true;
if ((arrayIndex < 0)||(arrayIndex > length - 1)){
isInRange = false;
}
if (isInRange == true){
MyList::array[arrayIndex] = passedValue;
}
return isInRange;
}
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
bool MyList::getElement(int passedIndex, int *iPtr){
bool isItValid = true;
if((passedIndex >= 0) && (passedIndex < length)){
*iPtr = MyList::array[passedIndex];
} else {
isItValid = false;
}
return isItValid;
}
Output

Floating Point Exception while reading from file

the program should read from 2 files (author.dat and citation.dat) and save them into a map and set;
first it reads the citationlist without problem, then it seems to properly read the authors and after it went through the whole list (author.dat) a floating point exception arises .. can't quite figure out why
seems to happen in author.cpp inside the constructor for authorlist
author.cpp:
#include <fstream>
#include <iostream>
#include "authors.h"
using namespace std;
AuthorList::AuthorList(char *fileName) {
ifstream s (fileName);
int idTemp;
int nrTemp;
string nameTemp;
try {
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
} catch (EOFException){}
}
author.h:
#ifndef CPP_AUTHORS_H
#define CPP_AUTHORS_H
#include <iostream>
#include <map>
#include <string>
#include "citations.h"
class Author {
public:
Author (int id, int nr, std::string name) :
articleID(id),
authorNR(nr),
authorName(name){}
int getArticleID() const {
return articleID;
}
std::string getAuthorName() const {
return authorName;
}
private:
int articleID;
int authorNR;
std::string authorName;
};
class AuthorList {
public:
AuthorList(char *fileName);
std::pair<std::multimap<int,Author>::const_iterator, std::multimap<int,Author>::const_iterator> findAuthors(int articleID) {
return authors.equal_range(articleID);
}
private:
std::multimap<int,Author> authors;
};
#endif //CPP_AUTHORS_H
programm.cpp:
#include <iostream>
#include <cstdlib>
#include "citations.h"
#include "authors.h"
#include "authorCitation.h"
using namespace std;
int main(int argc, char *argv[]){
CitationList *cl;
AuthorList *al;
//check if argv array has its supposed length
if (argc != 4){
cerr << "usage: programm article.dat citation.dat author.dat";
return EXIT_FAILURE;
}
//inserting citation.dat and author.dat in corresponding lists (article.dat not used)
cl = new CitationList(argv[2]);
al = new AuthorList(argv[3]);
try {
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
acl->printAuthorCitationList2File("authorcitation.dat");
} catch (EOFException){
cerr << "something went wrong while writing to file";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
All files:
https://drive.google.com/file/d/0B734gx5Q_mVAV0xWRG1KX0JuYW8/view?usp=sharing
I am willing to bet that the problem is caused by the following lines of code:
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
You are calling a member function using an uninitialized pointer. I suggest changing the first line to:
AuthorCitationList *acl = new AuthorCitationList;
Add any necessary arguments to the constructor.
While you are at it, change the loop for reading the data also. You have:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
When you do that, you end up adding data once after the end of line has been reached. Also, you seem to have the last line in the wrong place. It seems to me that it should be outside the while loop.
You can use:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
// Break out of the loop when reading the
// data is not successful.
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;
You can simplify it further by using:
while (s >> idTemp >> nrTemp >> nameTemp){
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;

Writing value to c style string in struct

For the life of me I can't figure out why the I can't write to a c style string inside of a struct.
College student - can't use string class, haven't learned pointers.
Help? 2 hours at trying to figure this out.
#include <iostream>
using namespace std;
void strCopy(char from[], char to[])
{
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
}
struct card
{
char suit[20];
char rank[20];
int cvalue;
char location[20];
};
void printCard(card card)
{
cout << card.rank << " of " << card.suit << endl;
}
int main()
{
// I don't think strCopy()'s the problem, I've used it with my last project.
cout << "Test strCopy()" << endl;
char str1[14] = "abcdefghijklm";
char str2[14];
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
// Now the negative.
card one;
one.cvalue = 2;
strCopy("Somewhere", one.location);
strCopy("Two", one.rank);
strCopy("Hearts", one.suit);
printCard(one);
}
// I don't think strCopy()'s the problem, I've used it with my last
project.
Wrong
for (int i = 0; i < 255; i++)
{
to[i] = from[i];
}
copies 255 characters, however that's not what you meant.
If here :
strCopy(str1, str2);
cout << " " << str2 << endl << endl;
Your're getting "correct" output, then you're just unlucky, since that invokes an undefined behavior, an you're writing off the end of the array.

Reading in Wav header - Not setting data size

I'm trying to read in the Header information of a .wav file.
If I have a .wav file that has a low sample rate (22050) it will read all the information in perfectly, however, if I have a higher Sample Rate (8000) then it fails to read in some information:
"dataSize" set's when using a 22050 .wav file however, when using a 8000 .wav file it does not get set and just displays some random numbers.. e.g. "1672494080" when the actual size is around 4k-4.5k in size.
Any suggestions to where I am going wrong?
EDIT:
#include <iostream>
#include <fstream>
#include <vector>
#include <inttypes.h>
#include <stdint.h>
#include <math.h>
using namespace std;
struct riff_hdr
{
char id[4];
uint32_t size;
char type[4];
};
struct chunk_hdr
{
char id[4];
uint32_t size;
};
struct wavefmt
{
uint16_t format_tag;
uint16_t channels;
uint32_t sample_rate;
uint32_t avg_bytes_sec;
uint16_t block_align;
uint16_t bits_per_sample;
uint16_t extra_size;
};
riff_hdr riff;
chunk_hdr chunk;
wavefmt fmt = {0};
uint32_t padded_size;
vector<uint8_t> chunk_data;
bool readHeader(ifstream &file) {
file.read(reinterpret_cast<char*>(&riff), sizeof(riff));
if (memcmp(riff.id, "RIFF", 4) == 0)
{
cout << "size=" << riff.size << endl;
cout << "id=" << string(riff.type, 4) << endl;
if (memcmp(riff.type, "WAVE", 4) == 0)
{
// chunks can be in any order!
// there is no guarantee that "fmt" is the first chunk.
// there is no guarantee that "fmt" is immediately followed by "data".
// There can be other chunks present!
do {
file.read(reinterpret_cast<char*>(&chunk), sizeof(chunk));
padded_size = ((chunk.size + 2 - 1) & ~1);
cout << "id=" << string(chunk.id, 4) << endl;
cout << "size=" << chunk.size << endl;
cout << "padded size=" << padded_size << endl;
if (memcmp(chunk.id, "fmt\0", 4) == 0)
{
if (chunk.size < sizeof(wavefmt))
{
// error!
file.ignore(padded_size);
}else{
// THIS block doesn't seem to be executing
chunk_data.resize(padded_size);
file.read(reinterpret_cast<char*>(&chunk_data[0]), padded_size);
fmt = *(reinterpret_cast<wavefmt*>(&chunk_data[0]));
cout << "format_tag=" << fmt.format_tag << endl;
cout << "channels=" << fmt.channels << endl;
cout << "sample_rate=" << fmt.sample_rate << endl;
cout << "avg_bytes_sec=" << fmt.avg_bytes_sec << endl;
cout << "block_align=" << fmt.block_align << endl;
cout << "bits_per_sample=" << fmt.bits_per_sample << endl;
cout << "extra_size=" << fmt.extra_size << endl;
}
if(fmt.format_tag != 1)
{
uint8_t *extra_data = &chunk_data[sizeof(wavefmt)];
}
}else if(memcmp(chunk.id, "data", 4) == 0) {
file.ignore(padded_size);
}else{
file.ignore(padded_size);
}
}while ((!file) && (!file.eof()));
}
}
return true;
}
int main()
{
ifstream file("example2.wav");
readHeader(file);
return 0;
}
OUTPUT:
size=41398
id=WAVE
id=fmt
size=18
padded size=18
chunk_data size=0
Where am I going wrong?
You have two problems with your code:
There is a 2-byte integer after the bitsPerSample value that you are not reading. It specifies the size of any extra data in that chunk. If the value of format2 indicates a PCM format only, you can ignore the value of the integer (it will usually be 0 anyway, but it may also be garbage), but you still have to account for its presense. The integer cannot be ignored for non-PCM formats, you have to read the value and then read how many bytes it says. You need to make sure you are reading the entire chunk before then entering your while loop, otherwise you will not be on the correct starting position in the file to read further chunks.
You are not taking into account that chunks are padded to the nearest WORD boundary, but the chunk size does not include any padding. When you call seekg(), you need to round the value up to the next WORD boundary.
Update: based on the new code you posted, it should look more like this instead:
#include <iostream>
#include <fstream>
#include <vector>
#include <inttypes.h>
#include <stdint.h>
#include <math.h>
using namespace std;
// if your compiler does not have pshpack1.h and poppack.h, then
// use #pragma pack instead. It is important that these structures
// be byte-alignd!
#include <pshpack1.h>
struct s_riff_hdr
{
char id[4];
uint32_t size;
char type[4];
};
struct s_chunk_hdr
{
char id[4];
uint32_t size;
};
struct s_wavefmt
{
uint16_t format_tag;
uint16_t channels;
uint32_t sample_rate;
uint32_t avg_bytes_sec;
uint16_t block_align;
};
struct s_wavefmtex
{
s_wavefmt fmt;
uint16_t bits_per_sample;
uint16_t extra_size;
};
struct s_pcmwavefmt
{
s_wavefmt fmt;
uint16_t bits_per_sample;
};
#include <poppack.h>
bool readWave(ifstream &file)
{
s_riff_hdr riff_hdr;
s_chunk_hdr chunk_hdr;
uint32_t padded_size;
vector<uint8_t> fmt_data;
s_wavefmt *fmt = NULL;
file.read(reinterpret_cast<char*>(&riff_hdr), sizeof(riff_hdr));
if (!file) return false;
if (memcmp(riff_hdr.id, "RIFF", 4) != 0) return false;
cout << "size=" << riff_hdr.size << endl;
cout << "type=" << string(riff_hdr.type, 4) << endl;
if (memcmp(riff_hdr.type, "WAVE", 4) != 0) return false;
// chunks can be in any order!
// there is no guarantee that "fmt" is the first chunk.
// there is no guarantee that "fmt" is immediately followed by "data".
// There can be other chunks present!
do
{
file.read(reinterpret_cast<char*>(&chunk_hdr), sizeof(chunk_hdr));
if (!file) return false;
padded_size = ((chunk_hdr.size + 1) & ~1);
cout << "id=" << string(chunk_hdr.id, 4) << endl;
cout << "size=" << chunk_hdr.size << endl;
cout << "padded size=" << padded_size << endl;
if (memcmp(chunk_hdr.id, "fmt ", 4) == 0)
{
if (chunk_hdr.size < sizeof(s_wavefmt)) return false;
fmt_data.resize(padded_size);
file.read(reinterpret_cast<char*>(&fmt_data[0]), padded_size);
if (!file) return false;
fmt = reinterpret_cast<s_wavefmt*>(&fmt_data[0]);
cout << "format_tag=" << fmt->format_tag << endl;
cout << "channels=" << fmt->channels << endl;
cout << "sample_rate=" << fmt->sample_rate << endl;
cout << "avg_bytes_sec=" << fmt->avg_bytes_sec << endl;
cout << "block_align=" << fmt->block_align << endl;
if (fmt->format_tag == 1) // PCM
{
if (chunk_hdr.size < sizeof(s_pcmwavefmt)) return false;
s_pcmwavefmt *pcm_fmt = reinterpret_cast<s_pcmwavefmt*>(fmt);
cout << "bits_per_sample=" << pcm_fmt->bits_per_sample << endl;
}
else
{
if (chunk_hdr.size < sizeof(s_wavefmtex)) return false;
s_wavefmtex *fmt_ex = reinterpret_cast<s_wavefmtex*>(fmt);
cout << "bits_per_sample=" << fmt_ex->bits_per_sample << endl;
cout << "extra_size=" << fmt_ex->extra_size << endl;
if (fmt_ex->extra_size != 0)
{
if (chunk_hdr.size < (sizeof(s_wavefmtex) + fmt_ex->extra_size)) return false;
uint8_t *extra_data = reinterpret_cast<uint8_t*>(fmt_ex + 1);
// use extra_data, up to extra_size bytes, as needed...
}
}
}
else if (memcmp(chunk_hdr.id, "data", 4) == 0)
{
// process chunk data, according to fmt, as needed...
file.ignore(padded_size);
if (!file) return false;
}
else
{
// process other chunks as needed...
file.ignore(padded_size);
if (!file) return false;
}
}
while (!file.eof());
return true;
}
int main()
{
ifstream file("example2.wav");
readWave(file);
return 0;
}