我正在尝试在php中编写一个结构,我知道在php中没有这样的东西,但至少让它以某种方式工作......
C ++:
// The struct
typedef struct data
{
char numbers[20];
char numbers2[50];
char number3[6];
char sometext[100];
}data_t;
data_t config;
char numbers[20] = "12345.12345";
char numbers3[6] = "12345";
char sometext[100] = "asdsadsad";
// Storing into struct
strcpy_s(config.numbers, numbers);
strcpy_s(config.numbers3, numbers3);
strcpy_s(config.sometext, sometext);
// Serializing struct to test.dat
ofstream output_file("test.dat", ios::binary);
output_file.write((char*)&config, sizeof(config));
output_file.close();
// Reading from it
ifstream input_file("test.dat", ios::binary);
input_file.read((char*)&master, sizeof(master));
cout << "NUMBERS : " << master.numbers << endl;
cout << "NUMBERS3 : " << master.numbers3 << endl;
cout << "SOMETEXT : " << master.sometext << endl;
cout << endl << endl;
现在在结构中存储c ++,然后读取它就可以了,但我想通过php存储在该文件中,然后从c ++中读取它,所以我有:
PHP:
$data = Array();
$data['numbers'] = "12345.12345";
$data['numbers3'] = "12345";
$data['sometext'] = "abcdfghs";
$fp=fopen("test.dat","wb") or die("Stop! i kill you...");
foreach($data as $key => $value){
echo 'written:'.$value;
fwrite($fp,$value."\t");
}
现在发生的事情是:
NUMBERS : 12345.12345 12345 abcdfghs
NUMBERS3 :
SOMETEXT :
所以你可以看到,它不好,我注意到从c ++写入文件(包含二进制数据)时有区别,而从php写入文件只是纯文本。
一些帮助会很复杂,非常感谢!
答案 0 :(得分:1)
numbers
成员分配20个字节。这意味着当你将它写入文件时,所有20个字节都被写入,写入12345.12345
之后就不会停止写入。另一方面,您的PHP代码准确写出$data['numbers']
中的内容并立即停止(好吧,添加无用的"\t"
后)。 &#34;二进制数据&#34;你在文件中注意到的只是在12345.12345
之后的剩余字节中碰巧存在于内存中的垃圾。其他领域也一样。numbers2
成员写入文件。您需要确保PHP代码写入终止NULL,将输出填充到字段与C ++结构中相同的大小,并以与C ++结构相同的顺序输出字段。您可以使用pack()
:
<?php
$data = array();
$data['numbers'] = "12345.12345";
$data['numbers2'] = '';
$data['numbers3'] = "12345";
$data['sometext'] = "abcdfghs";
$packed = pack('a20a50a6a100', $data['numbers'], $data['numbers2'], $data['numbers3'], $data['sometext']);
$written = file_put_contents("test.dat", $packed);
if($written === false) {
throw new RuntimeException("Failed to write data to file!");
} else if($written !== strlen($packed)) {
throw new RuntimeException("Writing to file was not complete!");
}
注意:为了获得最大的兼容性,您应该以一致的顺序将每个结构成员读/写到文件单独。否则,由于C ++字段填充/对齐,您可能会遇到问题。