Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inserting text into beginning of a file

Status
Not open for further replies.

Maurader

Technical User
May 8, 2002
59
CA
If I have a file that already contains text, is there a way to open it and write text to the beginning of the file?

Thanks
 
you can create a "temporary file" say "tmp.txt" open it in "append mod" write you current text in it and after that copy your original file to it say: "file.txt".
Now,close "file.txt" and open it in "writing mod" and copy "tmp.txt" to "file.txt".
 
is there a way to delete temp.txt afterwards?
 
Yes,you can use:

#include <windows.h>
.....
..
BOOL DeleteFile(
LPCTSTR lpFileName // file name
);
 
Or, if you don't want to #include <windows.h>, you can use the standard C functions unlink() or remove(). They are exactly the same, and you call them in the same way as DeleteFile:

remove(strFileName);
 
The way I have approached this problem in the past has been:

open temp file in append mode
write preprended data
open existing file in read mode
copy data from existing file to temp file
delete existing file
rename temp file to (previously) existing file name

This saves having to copy temp file to existing file.

OffByOne
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top