简体   繁体   中英

How to create a directory with unknown name using C language

In C, a directory is created like this:

mkdir("hello");

but what if we don't know the name of this directory (or it's told by user)? How can we define it to a computer? (%s is not working)

mkdir receives as parameter the name of the directory you want to create. Here the doc . So, you can define a variable to hold your input folder and pass it to the function

char path[30] = "path.to.dir";
mkdir(path, 0700);

Just create a string variable, store the string in that variable (whether it's from user input or hardcoded), then pass the variable to mkdir .

int main() {
  char str[10];

  scanf("%9s", str);
  mkdir(str, 0700);

  return 0;
}

I would recommend you to use snprintf so you can take any type of input.

#include <stdio.h>

int main() {
    char name[50];
    int i = 5;
    snprintf(name, 50, "dir.%i", 5);
    mkdir(name, 0700);
}

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