Reputation: 131
The problem that I am trying to solve:
Read a binary file and write the contents to a text file. The format of the contents within the binary file are specified by the user using an option, e.g. bin2txt.exe [filename] [/f]
, where /f
denotes the contents in the binary file are of float type.
My current algorithm:
declare:
typedef int datatype;
Use if...else
or switch...case
to modify datatype to float, unsigned int short etc. within the main code.
The problem:
datatype is successfully modified within the if...else
, but switches back to default (here, int) outside the if...else/switch...case
. This means, I could read binary to a vector then write the vector to a text file within the if...else
statements. But this way, the code becomes too repetitive (every if block will have a vector declaration, initialization, reading into vector and writing to text file.). It would be better to avoid such repetition.
Could someone please guide me to the write direction. ? Thanks.
Upvotes: 0
Views: 1293
Reputation: 66441
If you find yourself writing identical code except for the types involved, it's often a good candidate for a template.
A simple (untested) variant with no error checking or input verification:
template<typename T>
void convert(std::istream& in, std::ostream& out)
{
T data;
while (in.get(reinterpret_cast<char*>(&data), sizeof(data)))
{
out << data << std::endl;
}
}
int main(int argc, char* argv[])
{
std::ifstream input(argv[1], std::ios::binary);
std::ostream& output = std::cout;
std::string format = argv[2];
if (format == "/f")
{
convert<float>(input, output);
}
else
{
convert<int>(input, output);
}
}
Upvotes: 2