Reading binary file with fstream

扶醉桌前 提交于 2019-12-25 18:31:43

问题


I am reading a binary file with fstream and storing the information in an array of characters:

int dataLength = 32;
int counter = 0;
char data[dataLength];
char PMTone[dataLength/4];
std::fstream *fs = new std::fstream(inputFileName,std::ios::in|std::ios::binary);
fs->read((char *)&data, dataLength);
//of the 32 characters in data[], I need first, 5th etc elements:
//fill first pmt info
for(int i=0; i<(dataLength/4); i++){
PMTone[i]=data[counter];
counter+=4;
}

Now I'm setting PMTone[7] to be a as a test:

PMTone[7] = "a";

I get the error:

mdfTree.cpp:92:21: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]

I don't understand why the elements in PMTone[] are pointers to chars, when PMTone[] was defined as an array of chars.

When I do treat PMTone[] as an array of pointers to chars:

(*PMTone)[7] = "a";

I get another error that I don't understand:

mdfTree.cpp:91:18: error: invalid types ‘char[int]’ for array subscript

This seems to imply that the compiler doesn't consider PMTone[] to be an array at all, but simply a pointer to char.

Can anyone shed light on what is happening here? Why has PMTone[] become an array of pointers to chars?


回答1:


The literal "a" is not a character.

You need:

PMTone[7] = 'a';



回答2:


"a" is not a character it is an array of characters, 'a' followed by a null terminator.

You would need

 PMTone[7] = 'a';

with single quote. Incidentally I am surprised that it compiles earlier because dataLength wasn't declared as const.

PMTone itself is of type char[8] which is an array of characters. However it decays to a pointer and (*PMTone) is the first element, of type char




回答3:


An array is a way of storing values by having the address of the first element and accessing other elements by index. An array is basically a pointer to the first element.

When you create an array of chars

char arr[n];

program actually creates room for n characters in the memory.

When accessing arr[0] let's say like this:

arr[2] = 'a';

program is actually doing this:

*(arr + 2) = 'a';

meaning you are accessing a character which is stored 2 Bytes further from the memory location of the first element in the array (hence, the arr + 2), with the first element being arr[0]. The address of the first element is &(arr[0]) or, arr. Both are the same values.

The bug is where you tried saving a string "a" into a char.

The problem is you tried fixing it by dereferencing a dereferenced pointer:

(*PMTone)[7] = "a"; // is the same as
(PMTone[0])[7] = "a"; // when it should be 
PMTone[7] = 'a';


来源:https://stackoverflow.com/questions/13007862/reading-binary-file-with-fstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!