Results 1 to 3 of 3

Thread: [RESOLVED] editing a text file issue

  1. #1
    Join Date
    Sep 2013

    resolved [RESOLVED] editing a text file issue


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

  2. #2
    Join Date
    Aug 2004
    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:
    shell_exec('cat tmp.txt abc.txt > abc.txt');
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

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

    $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