在目录中创建文件(C) [英] create file inside a directory (C)
问题描述
我正在尝试在目录中创建一个目录和一个文件。以下是C中的代码,但是当我尝试编译它时,我收到了这个错误:对二进制的无效操作数(具有'const char *'和'char *')
I am trying to create a directory and a file inside the directory. Below is my code in C, but when I try to compile it, I got this error: invalid operands to binary / (have ‘const char *’ and ‘char *’)
char *directory = "my_dir";
struct stat dir = {0};
if(stat(directory, &dir) == -1)
{
mkdir(directory, 0755);
printf("created directory testdir successfully! \n");
}
int filedescriptor = open(directory/"my_log.txt", O_RDWR | O_APPEND | O_CREAT);
if (filedescriptor < 0)
{
perror("Error creating my_log file\n");
exit(-1);
}
感谢您的帮助
推荐答案
使用sprintf()或类似的方法创建pathFilename字符串:
use sprintf() or similar to create the pathFilename string:
char pathFile[MAX_PATHNAME_LEN];
sprintf(pathFile, "%s\\my_log.txt", directory );
然后
int filedescriptor = open(pathFile, O_RDWR | O_APPEND | O_CREAT);
注意 :如果您使用的是linux ,将 \\
更改为 /
,并将MAX_PATHNAME_LEN更改为260(或任何linux喜欢用于该值)。
Note: If you are using linux, change \\
to /
and MAX_PATHNAME_LEN to 260 (or whatever linux likes to use for that value.)
编辑 如果您需要在创建文件之前检查目录是否存在,这个:
EDIT if you need to check that a directory exists before creating a file there, you can do something like this:
if (stat("/dir1/my_dir", &st) == -1) {
mkdir("/dir1/my_dir", 0700);
}
这篇关于在目录中创建文件(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!