Question

I'm trying to redirect the input of my program. Here is the command I'm typing in the terminal:

./hello < name

"name" is a file containing a single string. hello is a compiled C program consisting of the following code:

int main(int argc, char *argv[])
{
        char message[100] = "Hello ";
        if(argc>1)
        {
                strcat(message, argv[1]);
                strcat(message, "\n");
        }
        else
        {
                strcat(message, "there\n");
        }

        printf("%s", message);
        return 0;
}

As far as I've understood the argument should now be the content of the name file. However in the program I can't detect any arguments (and prints out "Hello there").

Was it helpful?

Solution

That is going to read the file name and put it in your standard input, not in the first argument.

You can read it using fgets, getchar, scanf, etc.

The equivalent:

int c;

printf("Hello ");

while((c = getchar()) != EOF) {
    putchar(c);
}

puts("\nthere");

OTHER TIPS

Giving input redirection is different than providing argument.

Input redirection means the provided file will work as standard input.

so if you need filename as an argument, just write like this

./hello name

but by looking at your program, I will say you might have made a logical error. By running the command which I have mentioned above, you will get 'Hello name' printed on your screen. The actual name which you have saved in a file named 'name' will not get printed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top