运行 C 程序复制的二进制文件时出现段错误
Segmentation fault while running the binary file copied by C program
我有一个 C 程序来复制已编译(可执行)程序的二进制文件"Hello World!"。
下面是它的代码。
#include<stdio.h>
#include<stdlib.h>
int main()
{
/* File pointer for source and target files. */
FILE *fs, *ft;
char ch;
/* Open the source file in binary read mode. */
fs = fopen("a.out","rb");
if (fs == NULL)
{
printf("Error opening source file.\n");
exit(1);
}
/* Open the target file in binary write mode. */
ft = fopen("hello","wb");
if (ft == NULL)
{
printf("Error opening target file.\n ");
fclose(fs);
exit(2);
}
while((ch = fgetc(fs)) != EOF)
{
fputc(ch, ft);
}
fclose(fs);
fclose(ft);
return 0;
}
我已经编译成上面的程序并给了可执行文件名称'file10'。
a.out 是 hello world 程序的可执行文件(二进制)。
-bash-4.1$ ./a.out
Hello World!
-bash-4.1$
现在我运行上面的程序,这样a.out将被复制到"hello"二进制文件。
-bash-4.1$ ./file10
-bash-4.1$
这将创建二进制文件 "hello"。
接下来我尝试运行这个二进制文件。
-bash-4.1$ ./hello
-bash: ./hello: Permission denied
-bash-4.1$
我的权限被拒绝了。接下来我更改权限。
-bash-4.1$ chmod 777 hello
-bash-4.1$
现在当我 运行 "hello" 时出现分段错误。
-bash-4.1$ ./hello
Segmentation fault
-bash-4.1$
为什么会出现分段错误?不能像我在上面的程序中那样复制 C 程序的可执行文件吗?
谢谢。
您的变量 ch
类型错误。它的类型应该是 int
,而不是 char
。通过将 fgetc
的结果存储到 char
中,您将值 255 和 EOF
合并为一个值,从而在您第一次遇到值为 255 的字节时停止。
我有一个 C 程序来复制已编译(可执行)程序的二进制文件"Hello World!"。
下面是它的代码。
#include<stdio.h>
#include<stdlib.h>
int main()
{
/* File pointer for source and target files. */
FILE *fs, *ft;
char ch;
/* Open the source file in binary read mode. */
fs = fopen("a.out","rb");
if (fs == NULL)
{
printf("Error opening source file.\n");
exit(1);
}
/* Open the target file in binary write mode. */
ft = fopen("hello","wb");
if (ft == NULL)
{
printf("Error opening target file.\n ");
fclose(fs);
exit(2);
}
while((ch = fgetc(fs)) != EOF)
{
fputc(ch, ft);
}
fclose(fs);
fclose(ft);
return 0;
}
我已经编译成上面的程序并给了可执行文件名称'file10'。
a.out 是 hello world 程序的可执行文件(二进制)。
-bash-4.1$ ./a.out
Hello World!
-bash-4.1$
现在我运行上面的程序,这样a.out将被复制到"hello"二进制文件。
-bash-4.1$ ./file10
-bash-4.1$
这将创建二进制文件 "hello"。
接下来我尝试运行这个二进制文件。
-bash-4.1$ ./hello
-bash: ./hello: Permission denied
-bash-4.1$
我的权限被拒绝了。接下来我更改权限。
-bash-4.1$ chmod 777 hello
-bash-4.1$
现在当我 运行 "hello" 时出现分段错误。
-bash-4.1$ ./hello
Segmentation fault
-bash-4.1$
为什么会出现分段错误?不能像我在上面的程序中那样复制 C 程序的可执行文件吗?
谢谢。
您的变量 ch
类型错误。它的类型应该是 int
,而不是 char
。通过将 fgetc
的结果存储到 char
中,您将值 255 和 EOF
合并为一个值,从而在您第一次遇到值为 255 的字节时停止。