Dexter
Dexter

Reputation: 347

How to use redirection in C for file input

I need to get the file from the terminal, I know the command will look like:

./a.out < fileName.txt

I'm not sure how to use fgets() in my program to use the file requested from the terminal.

Upvotes: 17

Views: 78595

Answers (4)

Leandro Cadete
Leandro Cadete

Reputation: 23

You can use fread function

#include <stdio.h>
#include <malloc.h>

int main () {
    fseek(stdin, 0, SEEK_END);
    long size = ftell(stdin);
    rewind(stdin);

    char *buffer = (char*) malloc(size);
    fread(buffer, size, 1, stdin);

    printf("Buffer content:\n%s\n", buffer);
    return 0;
}

Upvotes: 0

frankscitech
frankscitech

Reputation: 81

Short Answer

open() your file, then dup2() your file descriptor towards Standard Input.

A dummy example

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
    int fd;
    char *command[] = {"/usr/bin/sort", NULL};
    if (close(STDIN_FILENO) < 0)
    {
        perror("Error close()");
        exit(EXIT_FAILURE);
    }
    if (fd = open(argv[2], O_RDONLY, S_IWUSR | S_IRUSR) < 0)
    {
        perror("Error open()");
        exit(EXIT_FAILURE);
    }
    if (dup2(fd, STDIN_FILENO) < 0)
    {
        perror("Error dup2()");
        exit(EXIT_FAILURE);
    }
    if (execv(command[0], command) < 0)
    {
        perror("Error execv()");
        exit(EXIT_FAILURE);
    }
    return EXIT_SUCCESS;
}

Output:

$ ./a.out < JohnLennon_Imagine_Lyrics.txt
Above us, only sky
A brotherhood of man
Ah
And no religion, too
And the world will be as one
And the world will live as one
But I'm not the only one
But I'm not the only one
I hope someday you'll join us
I hope someday you'll join us
Imagine all the people
Imagine all the people
Imagine all the people
Imagine no possessions
Imagine there's no countries
Imagine there's no heaven
It isn't hard to do
It's easy if you try
I wonder if you can
Livin' for today
Livin' life in peace
No hell below us
No need for greed or hunger
Nothing to kill or die for
Sharing all the world
You
You
You may say I'm a dreamer
You may say I'm a dreamer

Upvotes: 0

Pratik
Pratik

Reputation: 307

1.) you close stdin then assign a different file handler to it 2.) replace stdin with any other file handler using dup2 function you can achieve it

Upvotes: 1

Nigel Harper
Nigel Harper

Reputation: 1250

Using redirection sends the contents of the input file to stdin, so you need to read from stdin inside your code, so something like (error checking omitted for clarity)

#include <stdio.h>

#define BUFFERSIZE 100

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    fgets(buffer, BUFFERSIZE , stdin);
    printf("Read: %s", buffer);
    return 0;
}

Upvotes: 21

Related Questions