ifstream: reopening a file after it was renamed/deleted

U

ultr

Hello,

I was looking for a solution on http://www.cplusplus.com/ and serched
groups, but cannot find anything interesting.

My program opens an input file stream:
ifstream f( "in.txt" );
then goes to its end:
f.seekg( 0, ios_base::end );
and then, in a loop, waits for a new line to be put into this file,
and reads it:
string line;
while( true )
{
f.clear();
if( f.peek() != EOF )
{
getline( f, line );
cout << "> " << line << "\n";
}
usleep( 50000 );
}

However the file in.txt may be renamed or deleted, and a new, empty
one may be created in its place.
How can I detect it and close the current stream, and reopen it with
the new in.txt file?


Thank you.


Piotr D±browski
 
S

Sam

ultr said:
Hello,

I was looking for a solution on http://www.cplusplus.com/ and serched
groups, but cannot find anything interesting.

My program opens an input file stream:
ifstream f( "in.txt" );
then goes to its end:
f.seekg( 0, ios_base::end );
and then, in a loop, waits for a new line to be put into this file,
and reads it:
string line;
while( true )
{
f.clear();
if( f.peek() != EOF )
{
getline( f, line );
cout << "> " << line << "\n";
}
usleep( 50000 );
}

However the file in.txt may be renamed or deleted, and a new, empty
one may be created in its place.
How can I detect it and close the current stream, and reopen it with
the new in.txt file?

That's not a part of the C++ language per se, but rather depends on your
platform. On POSIX platforms, for example, you would use the stat() call,
and keep track of st_dev, and st_ino.

Unfortunately, there are a number of race conditions here due to the fact
that ifstream does not let you access the underlying file descriptor, unless
your C++ library gives you its own, specific, methods for doing so. The
correct solution is to run fstat() on the open file descriptor, and stat()
on the filename, then compare the two.


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQBH1E4Mx9p3GYHlUOIRAlJGAJ0S0iYk/HCT6jBOAJlHd3S4IcAVugCdGbMI
tJmKaK4si6ZRsVXUiPV6Jk0=
=GI/W
-----END PGP SIGNATURE-----
 
U

ultr

On POSIX platforms, for example, you would use the stat() call,
and keep track of st_dev, and st_ino.

That's what I was looking for. It solves the problem.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top