我正在尝试在 Windows 中使用 C 创建目录。有一些命令可以完美运行,但我首先想在某个目录中“cd”,然后创建该目录。
我正在使用此代码:
struct dirent *de;
DIR *dr = opendir("db/medicine/");
if (dr == NULL)
{
printf("Could not open current directory" );
return 0;
}
while ((de = readdir(dr)) != NULL)
{
printf("%s\n", de->d_name);
if(medicine.name == de->d_name)
{
directory_name_hit = 1;
printf("\n\n This medicine db already exists!\n");
printf("Please use edit menu for same medicine database. Redirecting ... ");
Sleep(2000);
admin_area();
}
else
{
directory_name_hit = 0;
char *temp1 = "cd \\db\\medicine\\ & mkdir ";
char *command = malloc(sizeof(strlen("cd \\db\\medicine\\ & mkdir "+strlen(medicine.name))));
strcpy(command, temp1);
strcat(command, medicine.name);
printf(command);
system(command);
}
}
closedir(dr);
我有以下内容:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dirent.h>
#include <string.h>
#include <dir.h>
#include <process.h>
当我运行代码时出现以下错误:
.
cd \db\medicine\ & mkdir adThe system cannot find the path specified.
..
cd \db\medicine\ & mkdir ad
Process returned -1073741819 (0xC0000005) execution time : 18.897 s
Press any key to continue.
为什么系统不运行正确的命令?它应该工作。路径是正确的,没有同名的子目录..
谢谢大家。
我找到了另一种更好的方法来做到这一点。以下是运行流畅的新代码:
// check if directory exists
// then make medicine directory
char *temp1 = "C:\\pharmaCMS\\db\\medicine\\";
char *result = malloc(sizeof(strlen(temp1) + strlen(medicine.name)));
strcpy(result, temp1);
strcat(result, medicine.name);
struct stat sb;
if (stat(result, &sb) == 0 && S_ISDIR(sb.st_mode))
{
printf("YES\n");
}
else
{
printf("NO\n");
CreateDirectory("C:\\pharmaCMS", NULL);
CreateDirectory("C:\\pharmaCMS\\db", NULL);
CreateDirectory("C:\\pharmaCMS\\db\\medicine", NULL);
CreateDirectory(result, NULL);
}
我注意到如果我们在 CreateDirectory 中添加完整路径,它不会创建根目录。为了创建每个目录,我们必须传递单独的命令。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句