简体   繁体   中英

problem in reading binary file (mix of ascii and binary)

My code for reading binary file is:

dataFile.open(fileName.c_str());
ifstream binData("Trafficlog_Data.txt", ios::in | ios::binary);  //binary data file 
if(!binData) { 
  cout << "Cannot open file.\n"; 
  return -1; 
} 
char *memblock;int nBytes =12;
memblock = new char [nBytes+1];
binData.read(memblock,nBytes);
memblock[nBytes+1]='\0';
std::string message;message.assign(memblock,nBytes);
printf("%s\n",message.c_str());

Now i have given a file as input which contain binary and ascii data
RFB 003.003
RFB 003.003
--some binary data--

When I am reading first 12 bytes of file which is "RFB 003.003\\n" but it prints "RFB 003.003=". Can anyone tell where im getting it wrong please. promblem is not with '\\0'. problem is it is not reading "RFB 003.003\\n" . IS it because this file is mix of binary and ascii data

你没有为memblock分配内存:

char *memblock = new char[nBytes+1];

Change:

memblock[nBytes+1]='\0';

to:

memblock[nBytes]='\0';

Let's say you read in six bytes to memblock , that goes into positions 0 through 5 inclusive:

  0   1   2   3   4   5    6    7
+---+---+---+---+---+----+---+---+
| H | E | L | L | O | \n | ? | ? |
+---+---+---+---+---+----+---+---+

(the ? areas still contain whatever rubbish was there before).

You then need to put the null terminator at position 6 rather than position 7 as your code is doing.

By placing the null terminator too far to the "right", you're including that first ? position, which could be holding anything.


That's what's causing your specific problem. You also have an issue that you're not allocating space to hold the data you're reading in. You just have a char * but you're not actually initialising it to point to usable memory. That's almost certainly going to cause problems.

Probably the simplest solution is to define it as:

char memblock[nBytes+1];

Although I see you've fixed that in your question now so it's of little consequence. The actual problem (putting the null byte at the wrong location) is covered above.

You're off-by-one: just do memblock[nBytes]='\\0'; The index starts at 0, so if nBytes is 0 you're writing at the first position, if nBytes is 1 you're writing at the second position and so on. By doing nBytes + 1 you actually jumped ahead one position and left one garbage byte at the end of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM