/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] editing a text file issue

hello,

Aim- To write a message “hello” in 1st line of text file which will automatic make the 1st line = “hello” , and the old text in 1st line which was “first” will come in second line , and the text in 2nd line will come to third line…. and so on..

example: we have a file abc.txt , which have 1st line = “hello”

now i want to write 1st line = “first” and the old text in 1st line which is “hello” must come in 2nd line automatic.

can anyone tell me what changes i need in the code below?

*[I want to do it without reading data of abc.txt file]*

$my_file = “abc.txt”;
$handle = fopen($my_file, ‘a’);
$ggg = “first”;
fwrite($handle, $ggg);
fclose($handle);

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogSep 18.2013 — I don't think there's any way to essentially implement an "insert mode" with PHP's file functions. I can't think of a way of doing it that does not involve reading the file, though you could limit memory usage by reading/writing it line by line to a temp file (which you first wrote the new line to), then renaming it to the original file's name.

You could do something in the OS shell, such as writing the new line to a file named tmp.txt, then using cat:
[code=php]
file_put_contents('tmp.txt', 'first');
shell_exec('cat tmp.txt abc.txt > abc.txt');
unlink('tmp.txt');
[/code]
Copy linkTweet thisAlerts:
@rahulalertpayauthorSep 18.2013 — hey thanks, i got the code

<?php

$file_data = "Stuff you want to addn";

$file_data .= file_get_contents('ok');

file_put_contents('ok', $file_data);

?>
×

Success!

Help @rahulalertpay spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...