php - 将随机访问文件代码迁移到 PHP

标签 php c++ file

#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;
}

上面的代码在文件上实现了一个二叉搜索树。它使用长度为 25 的字符数组作为节点。它假定文件的最大大小约为 16K。树以这种格式存储:

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

等等。在没有 child 的情况下,插入一个空节点。现在我必须在 PHP 中做同样的事情。这怎么可能,因为据我所知,PHP 不提供二进制文件访问。热切期待您的回复:)

编辑:如果我以二进制模式将整数写入文件,c/c++ 将写入 4 个字节,而不管该整数中存储的值如何。 PHP 将在文件中写入普通整数值,即如果值为 0 则为 0,如果值为 100 则为 100。这在使用 seek 时会出现问题,因为我不知道移动 put 指针的具体字节数。或者在这种情况下,我正在编写固定长度 = 25 的字符数组。我如何在 php 中执行此操作,因为变量根本没有类型?

最佳答案

PHP 确实 提供二进制文件访问。使用 fopen()并在模式字段中指定 'b'

要执行随机访问(即读/写),您应该在模式字段中指定'r+'(或'w+''x+' 'a+',具体取决于您想要做什么)。

要实际写入二进制数据(而不是该数据的文本表示),请使用 fwrite()pack() .

关于php - 将随机访问文件代码迁移到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8646490/

相关文章:

php - 如何使用 MySQL Query 和 PHP 分配排名

c++ - 使用 Xcode 作为 C++ 代码的 IDE

c++ - 函数参数求值顺序 : is it UB if we pass reference?

android - 在目录中写入文件

c - 使用 fscanf 读取空格

javascript - 如何在没有cronjob的情况下运行php页面脚本

php - 500内部服务器错误。 PHP提交页面

php - 避免循环查询 - 特定情况

c++ - 指向不同返回类型和签名的函数的指针映射

iPhone 存储图像的最佳方式