gpt4 book ai didi

C:为什么我在尝试创建新文件夹/目录时遇到段错误?

转载 作者:行者123 更新时间:2023-11-30 19:35:25 25 4
gpt4 key购买 nike

我尝试使用两个命令行参数创建一个新文件夹,一个是目标文件夹,另一个是源文件夹,但我收到“段错误(核心转储)”错误。您能帮我找出导致此错误的原因吗?代码如下。

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: ");
}

}
}

最佳答案

我已经尝试过,以下代码可以正常工作:

#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

关于C:为什么我在尝试创建新文件夹/目录时遇到段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42710756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com