execve() with redirected stdin from file
<p>Want to redirect stdin to file in execve(). So the program should be executed like this, I mean this is how I execute it in shell and it works: </p>

<pre><code>/opt/prog &lt; in.txt
</code></pre>

<p>Below is the code I wrote, but it doesn't seem to work. in.txt is binary file, I want to redirect it to stdin in executed program.</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;unistd.h&gt;
#include &lt;string.h&gt;

int main(void)
{
    int fd[2];
    pid_t pid;


    FILE *f = fopen("in.txt", "rb");

    if (pipe(fd) &lt; 0)
        return EXIT_FAILURE;

    if ((pid = fork()) &lt; 0)
        return EXIT_FAILURE;
    else if (pid != 0) { /* father */
        close(fd[1]);
        dup2(fd[0], STDIN_FILENO);
        execlp("/opt/prog", "prog", (char *)0);
        printf("done\n");
    } else { /* son */

        fseek(f, 0, SEEK_END);
        long fsize = ftell(f);
        fseek(f, 0, SEEK_SET);

        char *string = malloc(fsize + 1);
        fread(string, fsize, 1, f);
        fclose(f);
        close(fd[0]);
        write(fd[1], string, 11);
    }

    return EXIT_SUCCESS;
}
</code></pre>

<p><strong>Update 1:</strong></p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;unistd.h&gt;
#include &lt;string.h&gt;

int main(void)
{
    int fd[2];
    pid_t pid;

    FILE *f = fopen("in.txt", "rb");

    if (pipe(fd) &lt; 0)
        return EXIT_FAILURE;

    if ((pid = fork()) &lt; 0)
        return EXIT_FAILURE;
    else if (pid != 0) { /* father */
        fseek(f, 0, SEEK_END);
        long fsize = ftell(f);
        fseek(f, 0, SEEK_SET);

        char *string = malloc(fsize + 1);
        fread(string, fsize, 1, f);
        fclose(f);
        close(fd[0]);
        write(fd[1], string, 11);

    } else { /* son */
        close(fd[1]);
        dup2(fd[0], STDIN_FILENO);
        execlp("/opt/prog", "prog", (char *)0);
        printf("done\n");

    }

    return EXIT_SUCCESS;
}
</code></pre>