如何使用C在目录中创建文件

时间:2014-04-08 22:34:12

标签: c file directory

我正在尝试在目录中创建目录和文件。下面是我在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);
}

感谢您的帮助

3 个答案:

答案 0 :(得分:5)

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

在此处阅读更多内容: stat mkdir

答案 1 :(得分:1)

你应该做的事情如下:

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

然后在open函数中使用filepath

答案 2 :(得分:0)

请参考完整的解决方案:

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

运行程序并给出两个命令行参数:

  1. 第一个参数:DirectoryName
  2. 第二个参数:FileName

例如:编译后 ./executableName yourFolderName yourFileName