简体   繁体   中英

How to create a folder in c?

I tried to create a file and I did.

Now I'm trying to create the file inside a new folder, but this code doesn't work!


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

Maybe I need to create the folder before and only after the file, but I don't know how to achieve it... any help is appreciated!

This example makes the directory before it creates the file, and when it makes the file, note the double \\\\ in the file name to prevent an escape sequence being attempted from \\e , although it does work with a single / too.

#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上创建目录。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM