Alan wrote:
Dear All,
I'm trying to write a C++ that reads in hexadecimal characters from a
text file. For this I use the >> to read in a character at a time
inside a while loop that waits for eof to be reached. I'm able to read
in correctly about half my text file, then the program breaks out of
the while loop.
I presume this is due to the fact that one of the hex characters that
I'm trying to read in, is equals to eof. I've tried to get around this
problem, by using file pointers to determine the size of the file and
then use a for loop to read in the corresponding amount of characters.
This doing, I can copy half the initial text file into another file,
with the rest being filled with rubbish.
Does anyone have any ideas how I could get around this problem?
You should have posted a code fragment. From your description I can't
make
a suggestion what causes the problem.
If it is a text file, then reading characters from it will never result
a character being an
eof indicator because eof indicator is different from all characters
(it is of integer type).
Instead parsing the input yourself allow C++ standard library do it.
Try the following code:
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <cstdlib>
int main()
{
std::vector<int > hex_collection;
std::ifstream input_file("inp ut_file.txt");
if (input_file.is_ open() == false) {
std::cerr << "failed opening input_file.txt\ n";
exit(EXIT_FAILU RE);
}
// tell the input stream we will be reading integer values in
hexadecimal base
input_file.setf (std::ios_base: :hex, std::ios_base:: basefield);
std::istream_it erator<int> begin_input_ite rator(input_fil e);
std::istream_it erator<int> end_input_itera tor;
// read hex values into hex_collection vector
std::copy(begin _input_iterator , end_input_itera tor,
std::back_inser ter(hex_collect ion));
// output the values we read in.
std::copy(hex_c ollection.begin (), hex_collection. end(),
std::ostream_it erator<int>(std ::cout, " "));
std::cout << "\n";
}
P.Krumins