fstream ios::

Hi. I'm having trouble understanding ios:: fstream..
When i use ios::app, i can open any new file even if it does not exist in my folder and it wont display error from file.fail()
but when i use ios::ate, i can only open file that exist in my folder or else it will display the error from file.fail()

1
2
3
4
5
6
     char filename[15];
     cout <<"filename: ";
     cin >> filename;
     file.open(filename, ios::in | ios::out | ios::app);
     while (file.fail())
      cout <<"Error! File does not exist.";


how can ios::app check if the file exist or not?
I'm a complete beginner at fstream :'(
You could use a separate function to test whether or not the file exists, rather than trying to depend on some combination of file open modes.
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
#include <iostream>
#include <fstream>
#include <string>

bool file_exists( std::string fname )
{ 
    return bool(std::ifstream( fname )) ; 
}

int main()
{
    std::string filename;
    
    std::cout << "Please enter name of file\n";
    std::cin >> filename;

    if ( file_exists(filename) )
    {
        std::cout << "File already exists\n";
    }
    else
    {
        std::cout << "File does not exist\n";
    }
    
    
}
i see.. thank you for the help!

I have another question, is it possible to open the same file twice using different ios::?
like..
1
2
3
4
5
6
7
8
9
 
file.open("test.txt", ios::in);
//do something
file.close();
file.clear();

file.open("test.txt", ios::in|ios::out|ios::trunc|ios::app);
//... do something
file.close();


i tried compiling something like this.. but i only managed to read the file on the first one with ios::in and the second time, it does not write on the file even with ios::out..
From the reference page:
http://www.cplusplus.com/reference/fstream/ifstream/open/

If the mode has both trunc and app set, the opening operation fails.
thank you!!!! im sorry for the silly questions :'(
Topic archived. No new replies allowed.