c - 如何在c中创建文件夹?

标签 c windows

我尝试创建一个文件,我做到了。

现在我正在尝试在一个新文件夹中创建文件,但是这段代码不起作用!


#include <stdio.h>
#include <stdlib.h>

int main( void)
{
    FILE *fp;

    fp = fopen("txt/example.txt", "w"); // This only works without "txt/"

    fprintf(fp, "%s", "Some data here");

    fclose(fp);

    return 0;
}

也许我需要在文件之前和之后创建文件夹,但我不知道如何实现...感谢任何帮助!

最佳答案

此示例在创建文件之前创建目录,并且在创建文件时,注意文件名中的双 \\ 以防止从 \e 尝试转义序列,尽管它也适用于单个 /

#include <stdio.h>
#include <direct.h>
#include <stdlib.h>

void fatal(char *msg) {
    printf("%s\n", msg);
    exit (1);
}

int main(void) {
    FILE *fp;
    if (mkdir("txt"))
        fatal ("Error creating directory");
    if ((fp = fopen("txt\\example.txt", "w")) == NULL)
        fatal ("Error opening file");
    if (fprintf(fp, "%s", "Some data here") <= 0)
        fatal ("Error writing to file");
    if (fclose(fp))
        fatal ("Error closing the file");
    return 0;
}

关于c - 如何在c中创建文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438670/

相关文章:

c - 如何更改文件的扩展名

c++ - 将动态分配的二维字符数组传递给函数

c - 尽管指针已初始化,但出现神秘的段错误

c - 当时间过去时真正杀死当前进程

windows - HDC 是否使用 alpha channel ?

windows - Windows 7 格式化驱动器上的 FAT32 文件分配表大小超出 FAT32 规范

c - 使用 8 位整数作为标志掩码

c - 我正在将一个简单的 RNG 函数从 C 移植到 Go,结果不正确

c - 指定 C :\Program Files (x86)\gnuplot\bin in C programming using Geany 的文件路径

windows - WP7 去除黑边