user200081
user200081

Reputation: 563

File Redirection into Program

I'm having trouble with file redirection into my program. I have a Makefile called test and I want to redirect a text file into it as input. For example, I want to do:

test < file.txt

as input into my executable. However, I keep getting segmentation faults when I try to read the contents of file.txt. Here is my attempt:

int main(int argc, char* argv[])
{
  FILE *a;
  int count;
  a = fopen(argv[1], "r");
  for(n = 0; ; n++)
  {
    count = fgetc(a); // <- here is where my program segfaults
    if(feof(a))
      break;
  }
  return 0;
}

Might anyone know why this occurs?

Upvotes: 1

Views: 291

Answers (2)

The shell does not pass "<" and "file.txt" as arguments to the program, so your argv[1] is returning random garbage.

Instead of reading from a, you should read from stdin, which is automatically available and opened.

int main(int argc, char* argv[])
{
  int count;
  for(n = 0; ; n++)
  {
    count = fgetc(stdin); 
    if(feof(stdin))
      break;
  }
  return 0;
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

That's because the redirection is handled by the shell and not passed as an argument. When redirection is used, the file is used for stdin.

You should always check the result of function, in this case you try to call fopen with NULL as filename so it will return NULL leading to your segmentation fault.

Upvotes: 2

Related Questions