what will happened when delete an file opened by ofstream

hi

i want to save some runtime log into a file on embedded device, running on linux system. this file is opened by std::ofstream. for debug purpose i will copy this log file to my local PC, but this file may be delete by me by mistake, so is there any flag to check this file is still exist or stream is good. or there is some way to auto create a new file when it be deleted


Best Regards!

The file remains good so long as you have the file open, even if you delete it after opening it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std;

int main()
{
    ofstream outf("this_is_gone.txt");
    for ( int i = 0 ; i < 100 ; i++ ) {
        cout << "Line=" << i << endl;
        outf << "Line=" << i << endl;
        sleep(1);
    }
    return 0;
}


In one window

$ g++ bar.cpp
$ ./a.out 
Line=0
Line=1
Line=2
Line=3
Line=4
Line=5
///
Line=99


In another window
$ cat this_is_gone.txt 
Line=0
Line=1
Line=2
Line=3
Line=4
Line=5
$ rm this_is_gone.txt
$ ls -l this_is_gone.txt
ls: cannot access 'this_is_gone.txt': No such file or directory
$ lsof | grep a.out
a.out  11415  sc  cwd   DIR   0,44     40960    3670042 /home/sc/Documents
a.out  11415  sc  rtd   DIR    8,1      4096          2 /
a.out  11415  sc  txt   REG   0,44     13952    3676668 /home/sc/Documents/a.out
a.out  11415  sc  mem   REG    8,1   1088952    4201177 /lib/x86_64-linux-gnu/libm-2.23.so
a.out  11415  sc  mem   REG    8,1   1868984    4201172 /lib/x86_64-linux-gnu/libc-2.23.so
a.out  11415  sc  mem   REG    8,1     89696    4198616 /lib/x86_64-linux-gnu/libgcc_s.so.1
a.out  11415  sc  mem   REG    8,1   1566440    4460541 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
a.out  11415  sc  mem   REG    8,1    162632    4201144 /lib/x86_64-linux-gnu/ld-2.23.so
a.out  11415  sc    0u  CHR  136,2       0t0          5 /dev/pts/2
a.out  11415  sc    1u  CHR  136,2       0t0          5 /dev/pts/2
a.out  11415  sc    2u  CHR  136,2       0t0          5 /dev/pts/2
a.out  11415  sc    3w  REG   0,44       582    3680142 /home/sc/Documents/this_is_gone.txt (deleted)

The (deleted) part tells you that the file has gone from the file system.

Assuming you want to keep data written after the file was deleted (either intentionally or accidentally), you need to open/write/close.
You don't need to open/close every time, but you should certainly do so periodically.

This springs to mind.
https://www.google.com/search?q=linux+log+rotation



you can also set its (or a folder above its) permissions so it cannot be deleted accidentally.
Its none of my business but using linux and 'accidentally deleting files' is going to be a problem for you. Like a carpenter, measure twice, cut once, when it comes to deleting files. Which translates to 'do a ls with the delete wildcard you plan to use before deleting'.
Last edited on
Topic archived. No new replies allowed.