How to delete first line of text file?

I have a thread that write some float in text file every 1 second,I want to control size of file and if line over 60 delete first line for add new data, but after delete first line, new float not added to file (at the end of file)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
void *threadFunction(void* arg){
    ofstream out;
       out.open(BACKUP_FILE, fstream::app | fstream::out); 
       if(!out) {
         cout << "Cannot open backup.txt file.\n";
         return 0;
       }
       while(true){
         //calculate float
         //write in out
         fflush(stdout);
	 sleep(1);
     }
     out.close();
     pthread_exit(0);
}
size_t count_lines(const char *filename)
{
   ifstream myfile(filename);
   string line;
   size_t count = 0;
   while ( getline(myfile, line) )
   {
	   if ( ! line.empty() )
      ++count;
   }
    if (count>60){
        delete_line(filename, 1) ;
	      }

   return count;
}

// Delete n-th line from given file
void delete_line(const char *file_name, int n)
{
    // open file in read mode or in mode
    ifstream is(file_name);

    // open file in write mode or out mode
    ofstream ofs;
    ofs.open("/tmp/temp.txt", ofstream::out);

    // loop getting single characters
    char c;
    int line_no = 1;
    while (is.get(c))
    {

        // if a newline character
        if (c == '\n')
        line_no++;

        // file content not to be deleted
        if (line_no != n)
            ofs << c;
    }

    // closing output file
    ofs.close();

    // closing input file
    is.close();

    // remove the original file
    remove(file_name);

    // rename the file
    rename("/tmp/temp.txt", file_name);
}


Last edited on
> but after delete first line, new float not added to file
you destroyed the original file
you create another file give it the same name, but it's not the same file
so readjust your function to now use that update file
How can I readjust it ?
with
1
2
ofstream out;
 out.open(BACKUP_FILE, fstream::app | fstream::out); 

Is not readjust ?
¿are you executing that line after you rename the file?

1
2
3
4
5
6
7
8
const int size = 60;
float file[size];
int pos = 0;
//...
file[pos] = foo;
++pos;
if (pos == size)
   pos = 0;
Last edited on
In this case it would be most sensible to just keep the last 60 values in a queue and write out the whole thing every time.
Topic archived. No new replies allowed.