我正在尝试在新目录中创建一个文件,但我首先获取目录的路径,然后是文件名,但是当我尝试使用文件名创建目录时,它会失败,因为我可以' t将这两个变量添加到mkdir mkdir(direccionarchivo,'/',nombrearchivo);
#include <iostream>
#include <fstream>
#include <io.h> // For access().
#include <sys/types.h> // For stat().
#include <sys/stat.h> // For stat().
#include <string>
using namespace std;
int main() {
char respuesta,salida,direccionarchivo[100],nombrearchivo[100];
salida = 'e';
do
{
cout << "Escoja donde desea crear el archivo de notas" << endl;
cout << "Recuerde poner todo el directorio donde desea que se cree el archivo." << endl;
cout << "Ejemplo: C:\\Users\\omartinr\\Desktop" << endl;
cin >> direccionarchivo;
if ( access( direccionarchivo, 0 ) == 0 )
{
struct stat status;
stat( direccionarchivo, &status );
if ( status.st_mode & S_IFDIR )
{
cout << "El directorio si existe" << endl;
}
else
{
cout << "Esta direccion es un archivo" << endl;
}
}
else
{
cout << "La direccion escrita no existe" << endl;
cout << "Desea que sea creada?(S/N)" << endl;
cin >> respuesta;
if (respuesta == 's' || respuesta == 'S')
{
salida = 'f';
}
}
}while(salida == 'e');
cout << "Escriba el nombre del archivo con su tipo" << endl;
cout << "Ejemplo: notas.txt" << endl;
cin >> nombrearchivo;
mkdir (direccionarchivo,'/',nombrearchivo);
return 0;
}
答案 0 :(得分:0)
如果要连接两个字符串(即连接),可以使用strcat
函数。
您必须首先创建目录,然后在其中创建文件。您不能直接在不存在的目录中创建该文件。从命令行可以使用mkdir -p
您还确定要拨打的mkdir
功能吗?手册页提供了以下原型:int mkdir(const char *path, mode_t mode);
答案 1 :(得分:0)
使用mkdir时需要考虑几件事。首先,它不能用于在目录路径中创建多个目录。因此,如果目录tmp和blah尚不存在,mkdir("/tmp/blah/foo")
将失败。下面的程序是一个在路径上创建每个目录的示例(如果它不存在)。此外,您不希望使用mkdir创建文件名,因为它将创建为目录而不是文件。您需要使用open()或fopen()来创建/打开文件。 mkdir的linux手册页描述了两个参数:
NAME
mkdir -- make a directory file
SYNOPSIS
#include <sys/stat.h>
int mkdir(const char *path, mode_t mode);
DESCRIPTION
The directory path is created with the access permissions specified by
mode and restricted by the umask(2) of the calling process. See chmod(2)
for the possible permission bit masks for mode.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
int main (int argc, const char * argv[])
{
const char *path = "/tmp/blah/foo/bar/";
char bpath[1024];
sprintf(bpath, "%s", path);
printf("creating path %s\n", bpath);
char *s = bpath;
int scnt = 0;
int first = 1;
while (*s) {
if (*s == '/') {
if (scnt == 0 && first) {
/* skip root */
} else {
/* terminate partial path */
*s = '\0';
/* The behavior of mkdir is undefined for anything other than the "permission" bits */
struct stat sbuf;
if (stat(bpath, &sbuf) == -1) {
printf("creating sub path %s\n", bpath);
if (mkdir(bpath, 0777)) {
perror(bpath);
return -1;
}
} else {
printf("existing sub path %s\n", bpath);
}
/* restore partial path */
*s = '/';
}
}
/* advance to next char in the directory path */
first = 0;
++s;
++scnt;
}
return 0;
}
以下是该计划的输出:
creating path /tmp/blah/foo/bar/
existing sub path /tmp
existing sub path /tmp/blah
creating sub path /tmp/blah/foo
creating sub path /tmp/blah/foo/bar