# fwrite() point to beginning of file



## scrubbicus (Jan 23, 2009)

Trying to make a news program and since new news should go first and fwrite append puts newer stuff at the end of the document it's not working very well.

how do i append information to a document and make it go to the beginning? im lookin on php.net now and i cant find a way yet...

any help is appreciated! thanks

*EDIT*

so I got it to work but can anyone simplify it a bit more? mines like 15 lines of code. it
file_get_contents() of the current file into a variable
then it opens the file and writes over with the new information
then it appends to the file with the variable that held the old information before


----------



## Eriksrocks (Aug 7, 2005)

Try:


```
$file = fopen( $filename, "r+" );
fwrite( $file, $string );
fclose( $file );
```
This might not work, I haven't tested it yet.


----------



## colinsp (Sep 5, 2007)

The problem you have is that the standard mode for appending data to a file in php appends at the end. Therefore the only way you will be able to do what you want is to read the file in add your data to it and then write it back out. I think that you might need a bit more than Erik has suggested above.

Probably something like this:


```
$file = fopen( $filename, "r+" );
$content = file_get_contents($file,1);
$new_content = ("new_content.txt");//whatever your new content is
$string = $new_content + $content;
fwrite( $file, $string );
fclose( $file );
```
I just built on Erik's code. Again this is untested but should work.

Alternatively have a look at Newswriter a free news writing script that is easy to incorporate into any page.


----------



## Eriksrocks (Aug 7, 2005)

The fopen() mode of "r+" *should* place the file pointer at the beginning of the file, from which you could theoretically write from that point.

That's why I believe my code should work, but I haven't had time to test it.


----------



## colinsp (Sep 5, 2007)

Thanks for that Erik, that is what is great about this forum you learn something new every day.


----------



## MMJ (Oct 15, 2006)

If you place it at the beginning of the file it will overwrite whatever is at the beginning of the file.


----------



## Eriksrocks (Aug 7, 2005)

MMJ said:


> If you place it at the beginning of the file it will overwrite whatever is at the beginning of the file.


There you go. So I suppose the best way would be to use the workaround that you developed earlier.


----------

