Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在c语言中创建符号链接链_C - Fatal编程技术网

如何在c语言中创建符号链接链

如何在c语言中创建符号链接链,c,C,当我尝试执行此代码时,屏幕上会出现“分段错误”。有人能告诉我错误是什么吗?提前谢谢 #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char

当我尝试执行此代码时,屏幕上会出现“分段错误”。有人能告诉我错误是什么吗?提前谢谢

#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char * argv[]){
    int fd , i;
    int count= atoi(argv[2]);
    char name[50];
    char nname[50];
    strcpy(nname, "./lfille");
    strcpy(name, argv[1]);
    struct stat statbuf;
/*  if((fd=open(argv[1], O_RDWR)==-1)){
        fprintf(stderr, "Datei existiert nicht\n");
    }else*/ if((lstat(argv[1], &statbuf)==-1)){
        fprintf(stderr, "Error bei lstat\n");
    }else if(!(S_ISREG(statbuf.st_mode))){
        printf("%s ist nicht REG\n ", argv[1]);
        exit(1);
    }else{
        for(i=0; i<count; i++){
            printf("%s", nname);
            symlink(name, nname);
            sprintf(name,"%s", nname);
            sprintf(nname, "./lfille%d", i);
        }
    }
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
int-fd,i;
int count=atoi(argv[2]);
字符名[50];
字符名[50];
strcpy(nname,“/lfille”);
strcpy(名称,argv[1]);
结构stat statbuf;
/*如果((fd=打开(argv[1],O_RDWR)=-1)){
fprintf(标准,“日期不存在”);
}else*/if((lstat(argv[1],&statbuf)=-1)){
fprintf(stderr,“错误bei lstat\n”);
}否则如果(!(S_ISREG(statbuf.st_模式))){
printf(“%s ist nicht REG\n”,argv[1]);
出口(1);
}否则{

对于(i=0;i我用gnu gcc 4.8.2编译了源代码。
这个程序对我来说运行得很好。我认为你只向程序传递了一个参数,而不是两个。这就是为什么。我建议Weather Vane在他的回答中所说的。

参数
*argv[]
是一个字符串指针数组,其中
argc
通知了这个数组的长度

第一个元素
argv[0]
指向保存程序名的字符串。如果程序运行时提供了任何运行时参数,则会为每个参数提供一个字符串指针,并在
argc
中提供适当的值,以告诉您提供了字符串指针数组的多少个元素。如果没有提供程序参数,
*argv[]
数组的长度为1

如果试图访问本应提供的参数,则索引将超出数组的长度
*argv[]
这将导致未定义的行为。您将取消引用一个具有基本随机值的指针。这可能是良性的,也可能由于尝试访问内存而导致分段错误

我建议任何在运行时使用(比如2)个用户参数的程序都有类似的检查代码:

if (argc < 3) {
    printf ("Syntax should be: %s filename links\n", argv[0]);
    exit (1);
}
if(argc<3){
printf(“语法应为:%s filename links\n”,argv[0]);
出口(1);
}

在尝试使用
argv[1]
argv[2]
之前,必须检查
argc
的值。此处测试
if(argc>=3){…}
if(argc<3)返回1;
该代码支持在给定文件名和数字(链长度)的情况下创建符号链接链作为参数,您能告诉我您到底是如何通过这些参数的吗?如果您从命令行运行您的程序:program_name argument1 argument2。(.例如,假设我们的可执行文件名为symlin,您的文件名为link,您的链长或任意值为15,那么:
symlin link 15