开发者

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

开发者 https://www.devze.com 2023-02-21 07:50 出处:网络
My code for reading binary file is: dataFile.open(fileName.c_str()); ifstream binData(\"Trafficlog_Data.txt\", ios::in | ios::binary);//binary data file

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 "R开发者_如何学JAVAFB 003.003\n" but it prints "RFB 003.003=". Can anyone tell where i m 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


You didn't allocate memory for 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消