在目录中创建文件(C)

我正在尝试在目录中创建目录和文件。 下面是我在C中的代码,但是当我尝试编译它时,我得到了这个错误: 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字符串:

 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喜欢使用该值。)

编辑如果您需要在创建文件之前检查目录是否存在,您可以执行以下操作:

 if (stat("/dir1/my_dir", &st) == -1) { mkdir("/dir1/my_dir", 0700); } 

在这里阅读更多: statmkdir

你应该做一些事情,比如:

 char *filepath = malloc(strlen(directory) + strlen("my_log.txt") + 2); filepath = strcpy(filepath, directory); filepath = strcat(filepath, "/my_log.txt"); 

然后在open函数中使用filepath