将随机访问文件代码迁移到PHP
等等。如果没有子节点,将插入一个空节点。现在我必须用PHP做同样的事情。据我所知,PHP不提供二进制文件访问,这怎么可能呢。热切期待您的回复:) 编辑:如果我以二进制模式向文件写入一个整数,c/c++将写入4个字节,而不考虑该整数中存储的值。PHP将在文件中写入普通整数值,即,如果值为0,则为0;如果值为100,则为100。使用seek时会出现问题,因为我不知道移动put指针的具体字节数。或者在本例中,我正在编写固定长度=25的字符数组。由于变量根本没有类型,如何在php中执行此操作?来自php: 相比之下,您还可以使用“b”强制二进制模式,这将不起作用 翻译你的数据。要使用这些标志,请将“b”或“t”指定为 模式参数的最后一个字符 你说php不提供二进制文件访问是什么意思?php提供二进制文件访问。在模式字段中使用并指定将随机访问文件代码迁移到PHP,php,c++,file,Php,C++,File,等等。如果没有子节点,将插入一个空节点。现在我必须用PHP做同样的事情。据我所知,PHP不提供二进制文件访问,这怎么可能呢。热切期待您的回复:) 编辑:如果我以二进制模式向文件写入一个整数,c/c++将写入4个字节,而不考虑该整数中存储的值。PHP将在文件中写入普通整数值,即,如果值为0,则为0;如果值为100,则为100。使用seek时会出现问题,因为我不知道移动put指针的具体字节数。或者在本例中,我正在编写固定长度=25的字符数组。由于变量根本没有类型,如何在php中执行此操作?来自php
'b'
要执行随机访问(即读/写),应在模式字段中指定'r+'
(或'w+'
,'x+'
或'a+'
,具体取决于您想要执行的操作)
要实际编写二进制数据(而不是该数据的文本表示),请使用和。为什么不使用
fopen
和fwrite
?热切期待我们为您完成此任务?
#include <fstream>
#include <iostream>
using namespace std;
bool find_in_file(char*);
void insert_in_file(char*);
inline bool isNull(char* word);
int main()
{
char word[25];
for(int i = 0; i < 10; i++)
{
cin >> word;
if( find_in_file(word) )
cout << "found" << endl;
else
insert_in_file(word);
}
system("pause");
}
bool find_in_file(char* word)
{
ifstream file;
file.open("file.dat", ios::in);
char contents[655][25] = {0};
file.read(reinterpret_cast<char*>(contents), 16*1024);
file.close();
int i = 0;
while( !isNull(contents[i]) )
{
if( strcmp(contents[i], word) == 0)
return true;
if( strcmp(contents[i], word) < 0 )
i = 2*i + 2;
else
i = 2*i + 1;
}
return false;
}
void insert_in_file(char* word)
{
fstream file;
file.open("file.dat", ios::in | ios::binary);
char contents[655][25] = {0};
file.read(reinterpret_cast<char*>(contents), 16*1024);
file.close();
file.open("file.dat", ios::in | ios::out | ios::binary);
if( isNull(contents[0]) )
{
file.write(word, 25);
file.close();
return;
}
int parent;
int current = 0;
while( !isNull(contents[current]) )
{
parent = current;
if( strcmp( contents[current], word ) < 0 )
current = current*2 + 2;
else if ( strcmp( contents[current], word ) > 0)
current = current*2 + 1;
else
return;
}
int insertAt;
if( strcmp(contents[parent], word ) < 0 )
insertAt = parent*2 + 2;
else
insertAt = parent*2 + 1;
file.seekp(insertAt*25, ios_base::beg);
file.write(reinterpret_cast<const char*>(word), 25);
file.close();
}
inline bool isNull(char* word)
{
return word[0] == 0;
}
0 root
1 left child of root - L
2 right child of root - R
3 left child of L - LL
4 right child of L - LR
5 left child of R - RL
6 right child of R - RR