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);
}
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
Please Refer complete solution:
#include<stdio.h>
#include<string.h> // for string operations
#include<stdlib.h> //for malloc()
#include<fcntl.h> //for creat()
#include<sys/stat.h> //for struct stat, stat()
#include<unistd.h> //for close()
int main(int argc,const char **argv)
{
//variable declaration
int iFd = 0;
char *chDirName = NULL;
char *chFileName = NULL;
char *chFullPath = NULL;
struct stat sfileInfo;
//Argument Validation
if(argc != 3)
{
printf("[ERROR] Insufficient Arguments\n");
return(-1);
}
//argument processing
chDirName = (char *)malloc(sizeof(char));
chFileName = (char *)malloc(sizeof(char));
chFullPath = (char *)malloc(sizeof(char));
chDirName = strcpy(chDirName,argv[1]);
chFileName = strcpy(chFileName,argv[2]);
//create full path of file
sprintf(chFullPath,"%s/%s",chDirName,chFileName);
//check directory exists or not
if(stat(chDirName,&sfileInfo) == -1)
{
mkdir(chDirName,0700);
printf("[INFO] Directory Created: %s\n",chDirName);
}
//create file inside given directory
iFd = creat(chFullPath,0644);
if(iFd == -1)
{
printf("[ERROR] Unable to create file: %s\n",chFullPath);
free(chDirName);
free(chFileName);
free(chFullPath);
return(-1);
}
printf("[INFO] File Created Successfully : %s\n",chFullPath);
//close resources
close(iFd);
free(chDirName);
free(chFileName);
free(chFullPath);
return(0);
}
Run Program With giving two Command Line Arguments:
for example : after compiling ./executableName yourFolderName yourFileName
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.