【问题标题】:Writing a program that creates a directory and creates a file in that directory using c language [duplicate]使用c语言编写一个创建目录并在该目录中创建文件的程序[重复]
【发布时间】:2016-11-29 12:28:03
【问题描述】:

我一直在某个特定程序中尝试以下代码,但它只是创建目录而不放入它。

它所做的只是在目录之外创建文件,即作为文件夹的邻居。

mkdir(dir2, 0666);

DIR *dr1 = opendir(dir2);

fl = open("copy.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);

write(fl, buff, 512);

close (fl);
closedir(dr1);

【问题讨论】:

标签: c


【解决方案1】:

你想要这个:

mkdir(dir2, 0666);        // create directory
                          // construct the filename "directory/copy.txt"
char filename[200];
strcpy(filename, dir2);
strcat(filename, "/");
strcat(filename "copy.txt");    

fl = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);

write(fl, buff, 512);

close (fl);

这里不需要opendir ann closedir

Discalaimer:这是非错误检查和未经测试的代码,仅用于演示目的。

【讨论】:

    【解决方案2】:

    您需要将文件夹的路径附加到文件名:

    fl = open(strcat(directory_path, "/copy.txt"), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    

    其中directory_path是一个字符串,它存储了创建的文件夹的位置。

    char directory_path[100];
    strcpy(directory_path, dir2);
    

    strcat是用于连接两个字符串的函数,定义在string.h中。

    【讨论】:

    • 非常感谢它的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多