C language, how to check if a file exists and permissions information

Source: Internet
Author: User

Press function access, header file IO.h (Linux by using Unistd.h
int access (const char *filename, int amode);

A amode parameter of 0 indicates the existence of the check file, assuming the file exists. Returns 0. Does not exist, returns-1.



This function can also check other file attributes:

06 Checking Read and Write permissions
04 Checking Read Permissions
02 Checking Write permissions
01 Check Run Permissions
00 checking the existence of files

Experiment successfully under UNIX and VC.

The advantage is fopen (.., "R") is not good, when no read access to a failure.


And this even if this file does not have Read permission. It is also possible to infer whether the file exists in the

The presence returns 0. Does not exist return-1

#include <stdio.h>int main () {printf ("%d", Access ("Test.db", 0));}

Test procedure

#define __WINDOWS__//WINDOWS systems use//#define __LINUX__//LINUX systems using #ifdef __windows__#include <io.h> #endif #ifdef __linux__#include <unistd.h> #endif # include <stdio.h> #include <stdlib.h> #define FILE_NAME  " test.db "int main (void) {/* Check for existence */if ((Access (file_name, 0))! =-1) {printf (" file [%s] exists\n ", File _NAME);/* Check for Write permission */if ((_access (file_name, 2))! =-1) {printf ("FILE [%s] has write permission\n", file_name);} else{printf ("File [%s] has not write permission\n", file_name);}} else{printf ("File [%s] don ' t exists\n", file_name);}}


Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

C language, how to check if a file exists and permissions information

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.