如何使用C在目录内创建文件 [英] How to create file inside a directory using C

查看:125
本文介绍了如何使用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 如果您需要在创建目录之前检查目录是否存在,可以执行以下操作

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);
}   

在此处了解更多: 统计 mkdir

Read more here: stat, mkdir

这篇关于如何使用C在目录内创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆