C ++ basics: how to determine whether a file exists

Source: Internet
Author: User
C ++ basics: how to determine whether a file exists

A simple method:

# Include <iostream>
# Include <fstream>
Using namespace STD;
# Define FILENAME "Stat. dat"
Int main ()
{
Fstream _ file;
_ File. Open (filename, IOS: In );
If (! _ File)
{
Cout <FILENAME <"not created ";
}
Else
{
Cout <FILENAME <"already exists ";
}
Return 0;
}

Another method to use the C language library:

Function Name: Access
Skill: determine the object access permission
Usage: int access (const char * filename, int amode );
ProgramExample:
# Include <stdio. h>
# Include <Io. h>

Int file_exists (char * filename );

Int main (void)
{
Printf ("Does notexist. fil exist: % s \ n ",
File_exists ("notexists. fil ")? "Yes": "no ");
Return 0;
}

Int file_exists (char * filename)
{
Return (access (filename, 0) = 0 );
}

Access (filename, 0) 0 indicates checking whether the file exists

Finename file name mode:

0-check whether the file exists

1-check whether the file is running

2-check whether the file is writable

4-check whether the file is readable

6-check whether the file is readable/written for access

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.