Monday, May 24, 2010

Is there an efficient way to toss binary data in C++?

Below if the code I'm using. I wonder if anyone knows a faster way to do what I'm doing, which is taking in a file by reading its data byte by byte, and throwing out every other byte (so the final output is 1/2 the original).





I find that that way I'm doing it is really slow. Is there a way to do this faster? I think that reading the file in at once might speed things up so that cin doesn't have to be called over and over, but I don't know how to go about doing that.











#include%26lt;iostream%26gt;





using namespace std;





main()


{int i=0;


char ch;





while(cin.get(ch))


{if(i == 1)


{cout %26lt;%26lt; ch;


i = 0;


}


else if(i == 0)


{i = 1;


}





else {exit(-1);}





}





}

Is there an efficient way to toss binary data in C++?
You'd be better off reading the entire file into a dynamically allocated array to begin with, then using pointer arithmetic to remove the unnecessary bytes. File accesses are super slow, but if you read the entire thing first you can do it by reading in much bigger chunks and then just iterate over the list of read in data and skip every other byte.


No comments:

Post a Comment