C语⾔判断⽂件夹或者⽂件是否存在以及权限等信息access函数和删除⽂件或⽬录remove。。。
C语⾔判断⽂件夹或者⽂件是否存在以及权限等信息access函数和删除⽂件或⽬录
remove()函数使⽤实例
⼀、access函数可以判断⽂件夹或者⽂件是否存在以及获取权限等信息。
1、所需头⽂件和函数原型:
#include <unistd.h>
int access(const char *pathname, int mode);
2、参数说明:
filename:可以填写⽂件夹路径或者⽂件路径
mode:(F_OK) 只判断是否存在
(R_OK) 判断读权限
(W_OK) 判断写权限
(X_OK) 判断执⾏权限
3、返回值:
write的返回值⽤于判断⽂件夹是否存在的时候, 若存在或者具有相关权限,返回值为0;不存在或者⽆权限,返回值为-1。
⼆、remove()函数可以⽤来删除⽂件或⽬录
1、所需头⽂件和函数原型:
#include <stdio.h>
int remove(const char *pathname);
2、参数说明:
filename:可以填写⽂件夹路径或者⽂件路径
3、返回值:
On success, zero is returned.  On error, -1 is returned, and errno is set appropriately
三、实例测试:
#include<stdio.h>
#include<unistd.h>
char FILE_NAME[80];
int main()
{
printf("Please input the path's the file you want to delete:");
gets(FILE_NAME);
/* Check for existence
mode:
(F_OK)只判断是否存在
(R_OK)判断读权限
(W_OK)判断写权限
(X_OK)判断执⾏权限
*/
if( (access(FILE_NAME, F_OK )) != -1 )
{
printf( "File [ %s ] exists\n", FILE_NAME);
/* Check for write permission */
if( (access(FILE_NAME, W_OK )) != -1 )
{
printf( "File [ %s ] has write permission\n", FILE_NAME);
}
else
{
printf( "File [ %s ] has not write permission\n", FILE_NAME);
}
/* Check for read permission */
if( (access(FILE_NAME, R_OK )) != -1 )
{
printf( "File [ %s ] has write permission\n", FILE_NAME);
}
else
{
printf( "File [ %s ] has not write permission\n", FILE_NAME);
}
/* Check for execute permission */
if( (access(FILE_NAME, X_OK )) != -1 )
{
printf( "File [ %s ] has execute permission\n", FILE_NAME);
}
else
{
printf( "File [ %s ] has not execute permission\n", FILE_NAME);
}
}
else
{
printf( "File [ %s ] don't exists\n", FILE_NAME);
}
//RETURN VALUE
//On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.
if( remove(FILE_NAME) == 0 )
printf("%s has been Removed!\n", FILE_NAME);
else
perror("failed to remove the file!\n");
return 1;
}
四、执⾏测试
五、⼩结
上⾯的测试实例运⾏的结果是access函数可以判断⽂件或者⽂件夹是否存在以及获取权限信息;remove函数可以删除⽂件夹和⽂件。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。