[英]How to create file inside a directory using 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);
}
你应该做一些事情,比如:
char *filepath = malloc(strlen(directory) + strlen("my_log.txt") + 2);
filepath = strcpy(filepath, directory);
filepath = strcat(filepath, "/my_log.txt");
然后在 open 函数中使用 filepath
请参考完整的解决方案:
#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);
}
运行程序并给出两个命令行参数:
例如:编译后./executableName yourFolderName yourFileName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.