我正在尝试使用两个命令行参数创建一个新文件夹,一个是目标文件夹,另一个是源文件夹,但我得到了一个"分段错误(核心转储)"错误。你能帮我弄清楚造成这个错误的原因吗?代码如下。
int main(int argc, char **argv){
char *src = argv[1];
char *dest = argv[2];
DIR *srcdir;
DIR *destdir;
struct stat srcfile;
struct stat destfile;
struct dirent* directory;
if ((stat(argv[1], &srcfile) == -1) || (stat(argv[2], &src) == -1)){
exit(-1); //TODO: Change to proper error code
}
srcdir = opendir(src);
destdir = opendir(dest);
if ((srcdir == NULL)||(destdir == NULL)) {
printf("No such file or directory exist.\n");
exit(1);
}
char new_path[1024];
new_path[0] = '\0';
strcat(new_path, dest);
strcat(new_path, "/");
strcat(new_path, src);
if (stat(new_path, &destfile) == -1) {
if(mkdir(new_path, 0700) != -1){
mkdir(new_path, 0700);
}else{
perror("mkdir: ");
}
}
}
答案 0 :(得分:0)
我尝试过,以下代码正常工作:
#include<stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include<string.h>
int main(int argc, char **argv){
char *src = argv[1];
char *dest = argv[2];
DIR *srcdir;
DIR *destdir;
struct stat srcfile;
struct stat destfile;
//struct dirent* directory;
if ((stat(src, &srcfile) == -1) || (stat(dest, &destfile) == -1)){
exit(0); //TODO: Change to proper error code
}
srcdir = opendir(src);
destdir = opendir(dest);
if ((srcdir == NULL)||(destdir == NULL)) {
printf("No such file or directory exist.\n");
exit(1);
}
char new_path[1024];
new_path[0] = '\0';
strcat(new_path, dest);
strcat(new_path, "/");
strcat(new_path, src);
if (stat(new_path, &destfile) == -1) {
if(mkdir(new_path, 0700) != -1){
mkdir(new_path, 0700);
}else{
perror("mkdir: ");
}
}
return 0;
}
编译命令
gcc -Wall xxx.c