Answer the question
In order to leave comments, you need to log in
How to insert the value of a variable into the path (MkDir)?
I decided to get rid of the annoying routine, and as you know, laziness is the engine of progress. Since I am new to programming in C++, and even more so under Linux, I chose standard notepad and g++ for work. And then a problem arose - notepad creates temporary files (they are not visible graphically, but there are too many of them in the terminal, which confuses). I also decided to add the ability to create new projects (folder + file attached to it) to the program. I found it I can’t do it, but I can’t implement it in practice. Maybe seasoned programmers will tell the beginner how to insert the value of the variable into the path.
Below is a piece of code from the instructions:
#include <sys/types.h>
#include <sys/stat.h>
int status;
...
status = mkdir("/home/cnd/mod1");
cout<<"Enter name project=";
cin>>name;
path= MkDir("/home/Work/cpp/???");
Answer the question
In order to leave comments, you need to log in
In C++, a little shorter:
#include <string>
#include <iostream>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
int main()
{
std::string const path = "/home/Work/cpp/";
std::string name;
std::cout << "Input project name: ";
std::cin >> name;
if (name.empty())
{
std::cerr << "Empty file name" << std::endl;
return EXIT_FAILURE;
}
std::string const dir = path + name;
if (mkdir(dir.c_str(), 0755) == -1)
{
perror("Cannot create directory");
return EXIT_FAILURE;
}
std::cerr << dir << " created" << std::endl;
return EXIT_SUCCESS;
}
Too lazy to read books? Or is it necessary to take laboratory work at universities, but is it lazy to study?
I'm surprised there isn't a single correct answer. I was not too lazy and wrote in pure C.
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <linux/limits.h>
#define QUOTE_H(W) #W
#define QUOTE(W) QUOTE_H(W)
int main()
{
char name[NAME_MAX+1] = "";
char path[PATH_MAX] = "/home/Work/cpp/";
printf("Input project name: ");
if (scanf("%s"QUOTE(NAME_MAX), name) == -1)
{
fprintf(stderr, "Empty file name");
return EXIT_FAILURE;
}
size_t const max_name_len = PATH_MAX - 1 - strlen(path);
if (strlen(name) > max_name_len)
{
fprintf(stderr, "File name too long");
return EXIT_FAILURE;
}
strncat(path, name, max_name_len);
if (mkdir(path, 0755) == -1)
perror("Cannot create directory");
else
printf("'%s' created\n", path);
return EXIT_SUCCESS;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question