How to create file inside a directory using C

ⅰ亾dé卋堺 提交于 2019-12-18 09:00:28

问题


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

thanks for help


回答1:


use sprintf() or similar to create the pathFilename string:

char pathFile[MAX_PATHNAME_LEN];
sprintf(pathFile, "%s\\my_log.txt", directory );

then

int filedescriptor = open(pathFile, O_RDWR | O_APPEND | O_CREAT);   

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

Read more here: stat, mkdir




回答2:


you should do something such as:

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

and then use filepath in the open function



来源:https://stackoverflow.com/questions/22949500/how-to-create-file-inside-a-directory-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!