www.webdeveloper.com
Results 1 to 3 of 3

Thread: [RESOLVED] editing a text file issue

  1. #1
    Join Date
    Sep 2013
    Posts
    2

    resolved [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);

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,176
    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:
    PHP Code:
    file_put_contents('tmp.txt''first');
    shell_exec('cat tmp.txt abc.txt > abc.txt');
    unlink('tmp.txt'); 
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Sep 2013
    Posts
    2
    hey thanks, i got the code

    <?php
    $file_data = "Stuff you want to add\n";
    $file_data .= file_get_contents('ok');
    file_put_contents('ok', $file_data);
    ?>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles