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
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);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments