Q:

Input redirection in C programming?

I am trying to redirect a data file called data1 into my program, but I keep on getting a segmentation fault.
When I try ./w data1 then it reads it correctly but when I do ./w < data1 then the error pops up.
I have to use the second way for my assignment.
Here is what my code looks like:
int main(int argc, char *argv[])
{
 FILE *Q;
 Q = fopen(argv[1],"r");
}

A:

argv[1] points to the first parameter of your binary (without it's name), so in case of ./w < data1 it is missing. You're trying to access the "illegal" memory, so you get a segfault.
The mark < is a bash feature, it is not passed to C.
If you want to use such a redirection, just read from standard input and don't care about the file/argv. It means "take file data1 and pass it to descriptor 0, that is standard input".
You can use scanf or read(0, ...) to use the file's content.

A:

The reason your first command works is because you are providing an argument to your program (in your case, the filename) and your program uses that argument to open the file.
When you are using a redirect, you are redirecting stdin and stdout (which are accessed with functions like gets and printf) to the file, so you don't have to open any files in the program at all.

