简体   繁体   中英

How to get consistent responses from fstream?

When I read in information via fstream, it has ocurred twice in two different programs, that the input given to my program isn't stable, even if a given file doesn't change.

In my most recent program, which is concerned with audio-reading. I'm doing a simple check on the first four letters in the file. These letters are supposed to be RIFF, which they also are - I checked.

So, in order to check the format of a given binary file, I buffer the first four letters and see if they are equal to 'RIFF'.

char buffer[4];
std::ifstream in(fn,std::ios::binary);
in.read(buffer,4);
if(buffer!="RIFF"){//Always wrong atm
    std::cout << "INVALID WAV FILE: " << buffer << std::endl;
}   

When I first made the program, I recall this working properly. Now though, I get an error via my own cout:

INVALID WAV FILE: RIFFýfK    

Does anyone have any idea as to what has gone wrong? Perhaps a way to make fstream more consistent?

You're reading 4 characters but not adding a zero terminator , furthermore your comparison is wrong since you're not comparing strings equality, you should rather do:

char buffer[5];
std::ifstream in(fn, std::ios::binary);
in.read(buffer, 4);
buffer[4] = '\0'; // Add a zero-terminator at the end
if (strcmp(buffer,"RIFF")) { // If buffer isn't {'R','I','F','F','\0'}..
    std::cout << "INVALID WAV FILE: " << buffer << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM