Reputation: 233
I want to load a file with a number within it and use it as number(not as string). Is there any solution for this? The error I get
Call to a member function seek() on a non-object
My PHP Code
$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);
Upvotes: 0
Views: 132
Reputation: 6966
The answer is in the error message you're getting: it means you're calling a method, that is, an object's member function, for something which is not an object (in the sense of Object-Oriented Programming). $in
is not an Object of a Class, only a resource
.
Edit
Now I understand correctly the task you wanted to accomplish try this:
// 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);
That should work, yet not tested, to be honest. I hope you get the general idea.
Add
The code above reads all the contents of the emails file at once, into one (string) varible. You could then split it using \n
as a delimiter, something like $allEmails = split('\n', $content);
and have the emails in an array, through which you could loop.
Anyway, here is the same code but with while
loop, that is, reading the file line by line - would be good for very large file (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);
Upvotes: 0
Reputation: 185560
The file
$ cat /tmp/ll
9
The script :
<?php
$x = file_get_contents("/tmp/ll");
echo $x + 10;
?>
The output : 19
Upvotes: 1