0

我想加载一个包含数字的文件并将其用作数字(而不是字符串)。有什么解决办法吗?我得到的错误

Call to a member function seek() on a non-object 

我的 PHP 代码

$in = fopen('emails.txt','r');
$out = fopen('currentposition.txt', 'r+');
$pos = file_get_contents('currentposition.txt');
$in->seek($number1); 
while($kw = trim(fgets($in))) {
    //my code
    $position = $in->current();
    fwrite($out, $position);
}

fclose($in);
fclose($out);
4

3 回答 3

1

文件

$ cat /tmp/ll
9

剧本 :

<?php

$x = file_get_contents("/tmp/ll");
echo $x + 10;
?>

输出:19

于 2012-05-29T16:36:44.793 回答
0

答案在您收到的错误消息中:这意味着您正在调用一个方法,即对象的成员函数,用于不是对象的东西(在面向对象编程的意义上)。$in不是一个类的对象,只是一个resource.

编辑

现在我正确理解了你想要完成的任务试试这个:

// use w - to truncate when writing (overwrite), b - in case you ever run this on Windows
$recordFile = fopen('currentposition.txt', 'wbr');
$emailsFile = fopen('emails.txt', 'r');
$pos = trim(fgets($recordFile));
// if first time and there was no 0 in the currentposition.txt
if(!isset($pos))
    $pos = 0;

//set the pointer
fseek($emailsFile, $pos);

// read the contents;
$content = fread($emailsFile, filesize($emailsFile));

// get the current position of the file pointer
$pos = ftell($emailsFile);

// write the last position in the file
fwrite($recordFile, $pos);

fclose($recordFile);
fclose($emailsFile);

老实说,这应该有效,但尚未经过测试。我希望你能得到大致的想法。

添加

上面的代码一次将电子邮件文件的所有内容读取到一个(字符串)变量中。然后,您可以将其\n用作分隔符,例如$allEmails = split('\n', $content); 并将电子邮件放在一个数组中,您可以通过该数组进行循环。无论如何,这是相同的代码,但带有while循环,即逐行读取文件 - 对于非常大的文件(MBytes)会很好

// use w - to truncate when writing (overwrite), b - in case you ever run this on Windows
$recordFile = fopen('currentposition.txt', 'wbr');
$emailsFile = fopen('emails.txt', 'r');
$pos = trim(fgets($recordFile));
// if first time and there was no 0 in the currentposition.txt
if(!isset($pos))
    $pos = 0;

//set the pointer
fseek($emailsFile, $pos);


// while end of file is not reached
while(!feof($emailsFile)){
    // read one line of the file and remove leading and trailing blanks
    $kw = trim(fgets($emailsFile));
    // .... do something with the line you've read
    // get the current position of the file pointer
    $pos = ftell($emailsFile);    
    // you don't need to write the position in the $recordFile every loop!
    // saving it in $pos is just enough
}

// write the last position in the file
fwrite($recordFile, $pos);

fclose($recordFile);
fclose($emailsFile);
于 2012-05-29T16:52:15.603 回答
0

使用$pos而不是$number1...?

于 2012-05-29T16:38:23.613 回答