Click here to Skip to main content
15,915,093 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to see if a file exist before I copy the file to the path. I thought it would be simple but the method I tried got “std::ios_base::fail: non-standard syntax; use ‘&’ to create a pointer to member” was the error I got. I am probably being an idiot but I have only just started learning C++ so I still need to learn a bit.

What I have tried:

C++
Bool FileExists(const char * filename)
{
    Bool data = true;
    ifstream file(filename);
    If(file.fail)
    {
         Return data;
    }
    Else
    {
         Data = true;
         Return data;
    }
}

Sorry if this looks bad is because I am on my phone.
Posted
Updated 29-Jan-19 4:27am
v2

Here is what I use in windows :
C++
// see if a file is accessible and is not a directory

bool CheckFileAccess( PCTSTR filename )
{
    bool state = true;
    DWORD attrib = GetFileAttributes( filename );
    if( attrib == INVALID_FILE_ATTRIBUTES )
    {
        state = false;      // not accessible
    }
    else if( attrib & FILE_ATTRIBUTE_DIRECTORY )
    {
        state = false;      // it is a directory
    }
    return state;
}
 
Share this answer
 
Comments
Rick York 30-Jan-19 0:52am    
Given this, it is a simple extrapolation to arrive at an IsDirectory() type of function.
WOLF 2018 31-Jan-19 16:09pm    
Thanks I will give that a try
I found a Solution here I hope it works Checking whether a file exists or not[^]

Is a very simple method.
 
Share this answer
 
Comments
Richard MacCutchan 29-Jan-19 7:11am    
Did you notice that your code returns true in both cases?
CPallini 29-Jan-19 7:41am    
It actually Returns true. :-)
Richard MacCutchan 29-Jan-19 8:53am    
:)
[no name] 29-Jan-19 13:54pm    
I think it will not compile :-)
Usman Hunjra 29-Jan-19 12:53pm    
nice catch Sir .. ;)
Modern C++ makes your life easier: std::filesystem::exists - cppreference.com[^].
 
Share this answer
 
Comments
WOLF 2018 29-Jan-19 6:44am    
Unfortunately that didn’t work. My computer can’t find std::filesystem and I have included it.
CPallini 29-Jan-19 7:38am    
A C++17 compliant compiler is required.
Assuming you are using Visual Studio, see answer here: How to check if a file exists with stat in visual studio c++ 2010? - Stack Overflow[^]
 
Share this answer
 
Comments
WOLF 2018 29-Jan-19 6:46am    
Just finished reading this but I don’t understand where I can return true or false. I just want a simple method.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900