本文介绍了在c中创建文件及其父目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有找到与此问题相关的答案.
I didn't find any relevant answer for this question.
我想同时创建一个文件及其父目录:
I want to create a file and its parent directory at the same time:
示例:
FILE *fd2 = fopen("test/test", "w+");
不存在test/的地方.
where test/ doesn't exist.
有没有办法做到这一点?
Is there a way to do this?
推荐答案
在Linux中,您可以使用以下代码完成
In Linux you can do it with the following code
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
...
/* check if directory exist */
struct stat status = { 0 };
if( stat("test", &status) == -1 ) {
/* create it */
mkdir( "test", 0700 );
}
/* open file */
FILE *fd2 = fopen("test/test", "w+");
...
对于第一个if
语句中存在文件test
(stat
返回值为零)的情况,您还可以使用宏S_ISREG
和S_ISDIR
来检查这是文件还是目录. stat
结构的字段st_mode
.
For the situation when file test
exists in first if
statement (stat
return value is zero), you can also check if this is a file or a directory using macros S_ISREG
and S_ISDIR
and field st_mode
of stat
struct.
这篇关于在c中创建文件及其父目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!