Reputation: 11
Simply I have a text file which contains binary numbers. I need to read these numbers (without converting to integers or ASCII) and store them properly in an unsigned char Buf. After processing these data on an electronic board, a method reads the output from the board and store it in a Buf as well. So, I also need to write the data from the Buf to an output file.
first, I have doubt about the size of the buffer. The declaration is as shown bellow:
#define Buff_size (long) 255;
unsigned char buf[Buff_size];
What does 255 represent here? bits, bytes or words of unsigned char?
My data size is: 2048 (number) * 32 (bits) = 65536 bits. However, the size of the input data file is 68 KB. Which size is actually the data size and I should use as the buffer size?
I have tried some codes, and I can run the full code with no errors. however, when I print out the buffer I get incorrect data. This is the declaration of the input\output files:
// Open input and output files.
f_in.open(infilename, std::ios::out);
if (false == f_in.is_open()) {
printf("Error: Input file could not be opened.\n");
return(false);
}
f_out.open(outfilename, std::ios::in);
if (false == f_out.is_open()) {
printf("Error: Output file could not be opened.\n");
return(false);
}
I tried to read the input data from the input file f_in using the two following commands:
1) f_in.read((char*)buf, Buff_size);
2) //f_in >> buf;
When I tried to read the buf as: cout << buf << endl;
I got the correct data with some dummy data at the end using the first reading command. I'm assuming the size of the buffer is not approperate so I get these dummy data (very strange random characters). When I use the second command I get only first line of the input data file is printed out.
To summarise I need to read some data from a text file and store it in a buffer. Then write the output data line by line into an output file.
Upvotes: 0
Views: 1294
Reputation: 153840
The bits are clearly written as ASCII: you’ll want to read them formatted line by line and convert them to you unsigned char
s by decoding them individually. For example:
for (std::string line; getline(in, line); ) {
if (!std::all_of(line.begin(), line.end(),
[](char c){ return c == ‘0’ || c == ‘1’; })) {
// deal with unexpected line
continue;
}
for (int offset = 0; offset + 8 <= line.size(); offset += 8) {
unsigned char c = std::bitset<8>(line.substr(offset, 8)).value();
// do something with c
}
}
The declarations you wondered about are primarily a display of not understanding C++: there is no place in C++ to define constants using #define
. The semantic of the number clearly depends on how it is being used. As it is used on the line just following it it should be straight forward to determine what it is used for. Of course, there is also little place in C++ for fixed size arrays...
Upvotes: 0