Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.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 fopen的Linux分段错误_C_Segmentation Fault - Fatal编程技术网

C fopen的Linux分段错误

C fopen的Linux分段错误,c,segmentation-fault,C,Segmentation Fault,有人知道这个代码有什么问题吗?我总是犯错 int main (int argc, char **argv) { FILE *in, *out; in = fopen(argv[1],"r"); out = fopen(argv[2],"w"); fseek(in,0,SEEK_END); ... fseek(in,0,SEEK_SET); 是的。/a.out文件名1文件名2 我尝试将参数复制到字符串变量中,没有任何问题 char f1[100],

有人知道这个代码有什么问题吗?我总是犯错

int main (int argc, char **argv)
{
    FILE *in, *out;
    in = fopen(argv[1],"r");
    out = fopen(argv[2],"w");
    fseek(in,0,SEEK_END);
    ...
    fseek(in,0,SEEK_SET);
是的。/a.out文件名1文件名2


我尝试将参数复制到字符串变量中,没有任何问题

char f1[100],f2[100];
strcpy(f1,argv[1]);
strcpy(f2,argv[2]);
FILE *in, *out;
in = fopen(f1,"r");
out = fopen(f2,"w");
有人知道这个代码有什么问题吗

您在检查代码时没有任何错误。您假定对
fopen
的调用成功

in = fopen(argv[1],"r");
if ( in == NULL )
{
   // Problem opening the file.
   // Print the cause of the problem and exit.
   perror("Unable to open the file");
   exit(EXIT_FAILURE);
}

out

添加类似的代码我尝试将参数复制到字符串变量中,效果很好,这真的有必要吗?在这看起来很好之前,我从来没有在fopen中传递参数时遇到分段错误,可能打印出argc或argv以确保您确实收到了参数。我也尝试过这样做,它打印出argc和argv,但在调用fopen后,它会给我分段错误哪个fopen?可能是其中一个。。。在它们之间放置一些代码以查看哪个是崩溃的请编辑您的示例,使其最小、完整且可验证:。复制segfault的最小代码是多少?你试着调试它什么?使用调试器怎么样?文件存在,我尝试过这样做,但仍然给我错误。在这种情况下,我建议发布一个。文件可能存在,如果您没有写入或读取权限,它仍然可能失败