DevC++ ios::app not working

Hi, I'm kind of new to C++ programing but I'm facing a major problem.

I'm trying to append a file using ios::app in DevC++, but it just turncates the whole file when opened in any mode

Supposed the file contains:

This is a text file.



And say i wrote this code

1
2
3
4
5
void main()
{
    ofstream fout("File.txt",ios::app);
    getch();
}


and when I open the file after this, the contents of the file is completly erased.

Can anyone tell me what's going on?
Last edited on
Are you sure that the file contained data before you ran the program? Using the std::ios::app flag should preserve the file contents.

100% sure. I had written a list of names. All gone when I opened in ios::app OR ios::ate
It's hard to diagnose without a complete example to show the sequence of events.
Here's a simple example for test purposes:
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
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main() 
{
    const char * fname = "File.txt";
    
    // 1. create a new file, write some text and close the file.
    {
        ofstream fout(fname);
        fout << "This is a text file.\n";
    }
    
    // 2. open the file in append mode, write some more text and close.
    {
        ofstream fout(fname, ios::app);  
        fout << "Oranges and lemons.\n";      
    }
    
    // 3. open the file for input and display the contents.   
    ifstream fin(fname);
    
    string line;
    while (getline(fin, line))
        cout << line << '\n';
        
    return 0;
}

Output:
This is a text file.
Oranges and lemons.


@Chervil I had exactly tried that a day back! But it turncated the whole file.....

But today, It's doing fine......strange..

Anyways, thank you guys for helping me.
Topic archived. No new replies allowed.