Reputation: 50
In my code I have
for (int i = 0; i < 5; i++) {
ranInts= rand();//generate a random integer, store in ranInts
cout << ranInts<< " ";//Print out ints
binaryFile.write(reinterpret_cast <char *>(&ranInts), sizeof(int))//Write to file
}
The code to read is
binaryFile.seekg(ios::beg);//Set the pointer in file to beginning
for (int i = 0; i < 5; i++) {
binaryFile.read(reinterpret_cast <char *>(&ranInts), sizeof(int));
//reading each int moves the file pointer down 4 bytes, ready to get the next one
//display
cout << ranInts<< endl;
}
This works fine. What I want to do is go from the disk to the screen and leave the variable out of the loop.
Is this possible?
Upvotes: 2
Views: 184
Reputation: 726599
Yes, it is possible. Call std::copy
to copy an std::istream_iterator
based on your file into an std::ostream_iterator
based on cout
:
std::ifstream file("myinput.txt"); // Open your input file
file.unsetf(std::ios_base::skipws); // Make sure whitespace is not skipped
std::copy( // Call std:copy to copy the content
std::istream_iterator<char>(file)
, std::istream_iterator<char>()
, std::ostream_iterator<char>(std::cout, "")
);
Upvotes: 2
Reputation: 45
if you want to go from disk to the screen (two different devices ) its really not a problem.
note with this strategy you must know the lenth of the buffer. char buffer[50] make shure you add one for the eol char \n"
have fun.
Upvotes: 0