簡體   English   中英

如何在C中創建文件夾?

[英]How to create a folder in c?

我試圖創建一個文件,但是我做到了。

現在,我正在嘗試在新文件夾中創建文件,但是此代碼不起作用!


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

您需要使用CreateDirectory在Windows上創建目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM