linux中检查目录文件是否存在不存在则创建,并写入相关配置
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include<fcntl.h>
int create_param_file(const char *PathName); //检测目录与文件是否存在不存在则创建
int main(void)
{
create_param_file("etc/config/test"); //注意:1、文件目录最前面切勿加“/”
return 0;
}
int create_param_file(const char *PathName)
{
char dirName[256];
strcpy(dirName, PathName);
int i, len, fileSize, fd;
len = strlen(dirName);
for (i = 1; i < len; i++)
{
if (dirName[i] == '/')
{
dirName[i] = 0;
if (access(dirName, 0) != 0) // /etc/config/lianyunset
{
if (mkdir(dirName, 0755) == -1)
{
printf("mkdir error\n");
return -1;
}
}
dirName[i] = '/';
}
}
fd = open(dirName, O_RDWR | O_CREAT, 0664);
if (fd != -1)
{
fileSize = lseek(fd, 0, SEEK_END); // 文件定位到结尾,查看文件内容大小 配置完成值内容应大于10
printf("fileSize=%d \n", fileSize);
if (fileSize <= 10)
{
write(fd, "hello word !\n", strlen("hello word !'\n"));
}
close(fd);
}
如需测试可在linux系统中创建一个"test.cpp"文件将上面代码拷贝过去。然后gcc test.cpp 进行编译,执行编译后生成的a.out 文件:./a.out 。