简体   繁体   English

fopen 的 Linux 分段错误

[英]Linux Segmentation fault with fopen

Does anyone know what's wrong with this code?有谁知道这段代码有什么问题? I keep getting 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);

I did ./a.out filename1 filename2我做了 ./a.out filename1 filename2

I tried copying the arguments into string variables and I didn't have any problems我尝试将参数复制到字符串变量中,但没有任何问题

char f1[100],f2[100];
strcpy(f1,argv[1]);
strcpy(f2,argv[2]);
FILE *in, *out;
in = fopen(f1,"r");
out = fopen(f2,"w");

Does anyone know what's wrong with this code?有谁知道这段代码有什么问题?

You don't have any error checking code.您没有任何错误检查代码。 You assume the calls to fopen are successful.您假设对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);
}

Add similar code for out .out添加类似的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM