0

I have a C program to copy the Binary file of a compiled (executable) "Hello World!" program.

Below is its code.

#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;
}

I have compiled to above program and gave the executable name 'file10'.

a.out is the executable (binary) of a hello world program.

-bash-4.1$ ./a.out
Hello World!
-bash-4.1$

Now I run the above program so that a.out will be copied to "hello" binary file.

-bash-4.1$ ./file10
-bash-4.1$

This creates the binary file "hello".

Next I try to run this binary file.

-bash-4.1$ ./hello
-bash: ./hello: Permission denied
-bash-4.1$

I get permission denied. Next I change the permissions.

-bash-4.1$ chmod 777 hello
-bash-4.1$

Now when I run "hello" I get a segmentation fault.

-bash-4.1$ ./hello
Segmentation fault
-bash-4.1$

Why is there a segmentation fault? Can't executable of C program be copied like how I did in the program above?

Thanks.

1 Answer 1

4

Your variable ch has the wrong type. It should have type int, not char. By storing the result of fgetc into a char, you're collapsing the values 255 and EOF into a single value and thus stopping the first time you encounter a byte with value 255.

Sign up to request clarification or add additional context in comments.

2 Comments

but still it is not clear as how this causes a segfault?
@bare_metal what do you expect to happen when you cut off an executable partway through and then run it ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.