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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

append text to a file

Status
Not open for further replies.

incron

Technical User
Mar 16, 2002
60
0
0
US
Hi Guys

I only use C++ If i have to, and I am stuck with a problem. I am trying to append a line of text to a file. and I don't understand why the file is deleted when the second write is attempted. Meaning I first create and write a text file and then close the file.


But when I attempt to write to it again the original text file is deleted and the new text file (same name) is created with the contents of the second _write event. Below is the code it is fairly simple. By the way I also tried using the _O_APPEND mode option - the results were the same. Any ideas...??





Sleep(20);

if ((mcdb.GetDeviceCount())>0) //lets see if the system has any writable devices
{
char buffer[] = "This is a test of '_write' function";

int fh;
unsigned byteswritten;
if( (fh = _open( "Dynnonet.txt", _O_RDWR | _O_CREAT ,
_S_IREAD | _S_IWRITE )) != -1 )

{


if(( byteswritten = _write( fh, buffer, sizeof( buffer ))) == -1 )
perror( "Write failed" );
else
printf( "Wrote %u bytes to file\n", byteswritten );
Sleep(100);
_close( fh );
}




}






Sleep(5000);







Sleep(20);

if ((mcdb.GetDeviceCount())>0) //lets see if the system has any writable devices
{
char buffer[] = "This is a test part2 of '_write' function";

int fh;
unsigned byteswritten;

if( (fh = _open( "Dynnonet.txt", _O_RDWR | _O_CREAT ,
_S_IREAD | _S_IWRITE )) != -1 )

{
if(( byteswritten = _write( fh, buffer, sizeof( buffer ))) == -1 )
perror( "Write failed" );
else
printf( "Wrote %u bytes to file\n", byteswritten );
Sleep(100);
_close( fh );
}




}


 
>By the way I also tried using the _O_APPEND mode option - the results were the same.
By the way it works fine with _O_APPEND flag (VC++ 2008 and 2010).

Of course, you rewrite old contents of the file because file pointer points to the origin of the file after _open w/o _O_APPEND flag. Use _seek(fh,0,SEEK_END) call if you want to append data to the existent file w/o _O_APPEND mode.

Try to avoid using of non-standard low level <io.h> stuff (_open, _write et al). It's C++ (and XXI century here;)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top