Linux下的C++程序:判断目录/文件是否存在

本文中写了两个函数:

1)int IsFileExist(const char* path)

用于检查一个目录是否存在 -1:存在 0:不存在

2)int IsFileExist(const char* path)

用于检查文件(所有类型,包括目录类型)是否存在 -1:存在 0:不存在

如果不存在,可以用以下两种方式打印错误信息:

1)fprintf(stderr, "ERROR: %s\n", strerror(errno));

2)perror("ERROR");

程序代码:

#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>

#include <string.h>
#include <errno.h>

//检查目录是否存在
//-1:存在 0:不存在
int IsFolderExist(const char* path)
{
    DIR *dp;
    if ((dp = opendir(path)) == NULL)
    {
        return 0;
    }

    closedir(dp);
    return -1;
}

//检查文件(所有类型)是否存在
//-1:存在 0:不存在
int IsFileExist(const char* path)
{
    return !access(path, F_OK);
}

//
void Display(const char *path)
{
    if (IsFolderExist(path))
    {
        printf("Folder [%s] Exist!\n", path);
    }
    else
    {
        printf("Folder [%s]\n", path);
        //捕获errno方法1: fprintf
        fprintf(stderr, "ERROR: %s\n", strerror(errno));
    }

    if(IsFileExist(path))
    {
        printf("File [%s] Exist!\n", path);
    }
    else
    {
        printf("File [%s]\n", path);
        //捕获error方法2: perror
        perror("ERROR");
    }
}

int main()
{
    Display("/home/oracle/Documents");     //Current Folder
    Display("/home/12345edcba");           //Folder Not Exist
    Display("/home/oracle/Documents/a.c"); //Existing File

    return 0;    
}

运行截图:

191708_nOIm_1425762.png

END

转载于:https://my.oschina.net/Tsybius2014/blog/338232

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
主要功能: 1.读取配置文件程序 2.启动进程 3.监控进程,查看进程是否退出或者崩溃 4.若进程退出或者崩溃,重启程序。 5.支持sleep功能 6.进程若连续崩溃NUM_MAX次就进行相应的睡眠周期struct proc_struct proc: struct proc_ struct [mp: if(array) return 0 ∥切换到目录rse chdirldiri ifdp= opendir(dir}=NuLL}开日录/proc,矢败返回0,成功把描述指针返回给d return o 〃将φpro文件夹的描述符指针传递给reεddir,读取文件夹内容,循环赋值给结构体di while ((dirp= readdir(dp))= NULLY char data 301 ∥取文件名称赋值给数组daa(其中包含有进程的名称(pid sprintf(data, "s", dirp->d_name); ∥是否是由字符09组成的字符串,即得到所有进程的pid f((IsDigit(data)) prac =(struct proc_struct )4 malloc(sizeof(struct proc_struct) tmp proc: prac->pid =a: oi(dirp->d_name): It(proc tind( proc. array)) free( tmp); closedir(dp cturn proc_find 两个参数分别是两个进程描述的结构体指针 李比较两个进程pd是否相等 李*相等返回1,不相等返回0 幸率球事容球家草事家事球峰率享事球摩率球享享溶事*事卷寒球套事塞容寒/ int proc find( struct prcc_struct* src, struct proc- struct* dest) char buffer[40%6]. ps cmd[20] It fd. I sprintf(buffer, "ed/star", sre->pid); fd = open(butter, O_RDONLY) if(fd==-1) rerurn 0 memset(buffer, wO, sizeof(buffer)) len= read(fd, bufter, sizeof(bufter )-1) close(ld) if(l return 0: p= butter: p= strrchr(p, C) narq=strrchr(p, )) n=q-p-1 if (len >= sizeof, srt->name)) len= sizeof(src->name)-1 p+ l, len src->namelen]=0; =日 turn(strcmp( src->name, dest dest->name)==0)? 1: 0- 条善参数aay:让程结构体指针;参数sie进程列表数组aray的大小ie:配置文件路径 从配置文件得到指定的程序列表,将对应进程的信息填充到aray数组中 羋执行成功返回进程个数,执行失败返回0 int get_ proc( struct proc_struct array, int size, char file intnRet=o if(! array I‖(si 0)l‖fhle myprinttf"invalid parameterin retun o char line[4096]; FILE fp= fopen(file, T"); if(fp) printf("open file cs fail\n", file) return U memset(line, 0, 4095); while(fgets(lire, 4095, tp)&& nRet size) memcpy(void s)[(&arraylnRet )->cmdline), (void")line, strlen(line)-2 ) tmp= strrchr(line, / ) Lmp += I: memcpy((&array inRet))->name, tmp, strlen(tmp)- 2) nRet++ ); return(nReL); 康棒串串浓凉率旅浓串底率卖毒志着旅浓浓准溶房表 装 startProc *卷参数proc:要启动的进的结构体描述指针 启动程序 执行成功返回1,子进程退出 宗塞家康家家家家家家家家宋家家聚家苯家球察塞家塞家家容家塞家家家家室家家察家家家聚家聚寒撑家装家掌建察家家室事 int startProc (struct proc_ struct* proc, struct proc _struct*must_run_ proc int mIst_run_size static inti=d if( proc)return 0 if(strlen(proc->cmdline I<=0) return 0; int pid= forko: 〃进程内部返回值为0,返回给父进程的为自己的pid inta〓 if(pid pid= fork( ifpd≡0 execl(char")proc->cmdline,(char")prDc->name,NULL); ∥exit: It(o): sleep42片 waiL(NULL) sleep( I: if(i== must run size -1) if(check proc(&must run proc[i])==0) startProc( &mtust_run_proeli], must_run_prce, must_run_size); el if(i== must run size-11 i= else 1++ start Proc( &must_run_proclil, must_run_ proc, mustrun_ _size); !**幸幸串率幸米幸*家*幸毕零*幸幸半字幸字华米*幸半孝率非幸零幸学幸幸车 3a*8*daemon init 幸*启动配置文件当中的需要守护的程序 执行成功返回1,中途出错,返回-1 长界零家墨军零家零率家三哮零座零率零零容岸军零罕型率零零零零牢察座察零零零零季球军零容零 int moniter_ run(struct proc_struct"must_run_proc, int proc_ size) nti=0: for(i=0; i< must_run_size: i ++) ∥监控程序是否正在运行 if(check_ proc(&(must un_ proc[il))<=o) ∥厘新片动程序 startProc(&' must run procli]), must run proc, proc size return I: 幸*事率事率率**率**字幸学摩*率*幸幸学幸半*率幸字****幸中*幸学幸 春*着*信号处理函数 exit_proc 翥安全结束监控的程序 4来没有返回值 告参毒萨响幸帝称昨嗜幸古称索点响卷南都南请南幸难布际本啪昨青市南动南香请非市赤南本 void exit_ proc(int ar InL I struct proc struct proc for(i=0; i< must run_ Size: i++) proc=&(must_run_proc[i]): kill(proc->pid, SIGTERM); exit flag=I exit(o): void exit_proc(int pid 要main L.获取程序列表2启动进程3.监控进程,若程序岀或崩溃,重新启动程序4.收到退 出信号,安全结束监控程序 成功返回1,失败返回0 零牢容容家容字家容容察*禁容容字哮零常字容容容家察容牢容零容容容容容牢字家客字容牢容零容*字容客字容容字容家容容字岩 static void run moniter( void data) 读取程序列表 must_ run _size get proc(must_run_proc, sIZE, data if(rmust run Sizc <=1) return o struct sigaction act, oldact act,sa handler= exit_proc act. sa flags =SA ONESHOT sigaction(SIGTERM, &act, NULL) sigaction(SIGINT, &act, NULL) sigaction(sIGHUP, &act, NULL); 检测并启动未启动的程序 moniter_ run(must run proc, must run slze) eturn null int creat and run moniter(char * file) 开线程: pthread_t moniter_ thread if(pthread_create(&moniter_thread, NULL, run_moniter, file)==0) printf("thread create Ok, check thread start \n") return printf( thread check create Errin"): return -I 零零零零享享事职增零半非寥零享半容零摩率率零享剩率容半半享零半率零半率零率辱寒零享 要 IsDigit 参茶爹数a字符串的地址 *判断字符串是否有纯数字字符组成 春客是纯数字返回1,不是纯数字返回0 喜非要串思率串串串串家串润串串串串串串毒毒喜串串最率毒串串踪串率串串非球毒串妆串串毒串串影零串串毒事串 static int IsDigit[char aD) Int size ∥得到当前字符串的长度 size= strlen(a: ∥若字符串长度为0,则直接返回0:即宇符串为空则返回0: if(size ==0) return 0; ∥循环遍历整个字符串 forli=0; i< Size; i++) ∥如果字符小于字符0,或者大于字符9,则返回0 if(ai]<ol ai>9) retum ∥走到这一步说明字符串由字符09组成,返回1 return l; 主进程源文件:man,c main.c #include"process, h Include <stdio. h> include <stdlib h> 甲 include< unistd. I> 甲 nclude< signal> 却 nclude <sys/ ypes,h include <sys/stat. h> 甲 include< tenth> int main(void) creat_and_run_moniter("proclistini") while(l) sleep(D) turn 以上内容是程序全部源文件
您可以使用 C++文件流来实现向当前用户目录写入 txt 文件,示例代码如下: ```c++ #include <fstream> #include <iostream> #include <unistd.h> // 获取当前用户目录 #include <sys/stat.h> // 创建目录 #include <sys/types.h> using namespace std; int main() { string homedir = getenv("HOME"); // 获取当前用户目录 string filepath = homedir + "/example.txt"; // 文件路径 string dirpath = homedir + "/example_dir"; // 目录路径 // 创建目录 if (mkdir(dirpath.c_str(), 0777) == -1) { cerr << "创建目录失败!" << endl; return 1; } // 打开文件 ofstream outfile(filepath); if (outfile) { // 判断文件是否成功打开 outfile << "Hello, world!"; outfile.close(); // 关闭文件 cout << "写入成功!" << endl; } else { cout << "打开文件失败!" << endl; } return 0; } ``` 在上述代码中,我们首先使用 `getenv("HOME")` 函数获取当前用户目录,然后拼接文件路径和目录路径。接着,我们使用 `mkdir` 函数创建目录,如果创建失败就输出错误信息并退出程序。最后,我们使用文件流打开文件,如果成功就写入字符串并关闭文件,否则就输出错误信息。 需要注意的是,在使用 `mkdir` 函数创建目录时,需要在第二个参数中指定目录的权限。在上述代码中,我们使用 `0777` 来指定目录权限,其中 `0` 表示权限位,`777` 表示读、写、执行权限都开放。如果不想让其他用户有访问权限,可以将 `0777` 替换为 `0700`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值