Sign in to follow this  
dragonbide

File I/O question

Recommended Posts

Hi. It's been a long time since I've delt with file io in c++. Can someone think of a good way to read in a file line that looks like: 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 into a 16 element int array? Thanks alot.

Share this post


Link to post
Share on other sites
If each number is only a 1 or a zero, just read in 31 bytes, and read every second byte.
Otherwise, just read chars into a buffer until you his a space, then use atoi() on the buffer to get the integer value.
I never do C++ I/O, I much prefer the C functions (fopen, fread, etc) so I can't help you with that aspect.

Share this post


Link to post
Share on other sites
I'm assuming you are trying to actually load in the binary data, not text :)

Well with the base file IO functionality the lowest you'll be able to load in are bytes (char, unsigned char) so load in the two of those and then you'll need to isolate each bit, something like.


for (i = 0; i < 8; i++) // 8 bits per byte :)
{
if (byte & 0x80) // read the highest bit (the 128 bit)
{
array[array_start + i] = 1;
}
else
{
array[array_start + i] = 0;
}

byte = byte << 1; // next bit to higest
}


for the first byte set array_start to 0, second one to 8.

you can also do this in reverse (load from lowest to highest) by simply checking if the byte is even or odd (byte % 2) then shift the other way.

Hope that helped


Share this post


Link to post
Share on other sites
Quote:
Original post by dragonbide
Hi. It's been a long time since I've delt with file io in c++. Can someone think of a good way to read in a file line that looks like:
0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0
into a 16 element int array? Thanks alot.


if it's a text file and each of those values is sperated with whitespace then this will do it:


#include <algorithm>
#include <iterator>
#include <vector>
#include <fstream>
#include <iostream>

int main() {

std::ifstream in("test.txt");

std::vector<int> vec_of_ints;

std::copy(std::istream_iterator<int>(in),
std::istream_iterator<int>(),
std::inserter(vec_of_ints, vec_of_ints.begin()));

std::copy(vec_of_ints.begin(),
vec_of_ints.end(),
std::ostream_iterator<int>(std::cout, ", "));

in.close();

return 0;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this