1

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?

1
  • 1
    Thank you thank you thank you for doing eof correctly! Commented Nov 28, 2012 at 9:03

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

fgetc is undefined with NULL as its argument (a "specialisation" of a non-stream argument, of course), then? That would appear to be the implication from the docs, though for some reason I'm surprised.
@LightnessRacesinOrbit I don't have the C standard, but none of the references I have access to (including the POSIX standard which should be a copy of the actual C standard) mentions anything about using NULL as the file pointer, so I would say it's definitely undefined behavior. Presumably some implementations behaves as it's a proper pointer and accesses it without any checking.
Just trying to figure out why I'm surprised. I'd have expected a "safe" result possibly because of the tendency of POSIX functions to bail on error, including fgetc which is defined to return EOF on error (I'm not claiming that this should include the bad-input case; it's just interesting)
7.19.7.1 doesn't mention any semantics for this case. Still surprised, though! Oh well.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.