您的位置:首页 > 其它

删除指定目录下的某个普通文件

2014-06-14 18:40 267 查看
描述:先判断指定目录下是否存在该文件,如果不存在,则返回错误。如果存在,那么调用unlink函数或remove函数来删除。

要求:将文件的绝对路径和文件名做输入参数,打印信息表明是否删除成功。

知识点:

#include <unistd.h>

#include<stdio.h>

int unlink(const char * pathname)

int remove(const char * pathname)

代码:

#include<stdio.h>

#include<stdlib.h>

#include<sys/stat.h>

#include<unistd.h>

#include<sys/types.h>

#include<dirent.h>

#include<string.h>

#define MAX 1024

int delete(char *path,char * name)

{

DIR *dir;

DIR *d;

struct stat st;

struct dirent *entry,*en;

char fp[MAX];

dir=opendir(path);

if(dir==NULL)

{

return -1;

}

while((entry = readdir(dir)) != NULL)

{

if((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0))

{

continue;

}

sprintf(fp,"%s/%s",path,name);

stat(fp,&st);

if(S_ISREG(st.st_mode) & (strcmp(name,entry->d_name)==0))

{

remove(name);

printf("删除文件%s成功!\n",name);

exit(0);

}

}

printf("文件%s不存在\n",name);

return 0;

}

int main(int argc,char * argv[])

{

if(argc==3)

{

delete(argv[1],argv[2]);

}

else

printf("输入参数不对!\n");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: