-1

For example, I run my program like:

program.exe < text.txt

I want the program to read from file text.txt. How do I begin doing this?

yezi3
  • 1
  • 1
  • 3

2 Answers2

2

Ok, as this is a textfile, you probably want to read it line by line, so

char buf[1024];
while (fgets(buf, 1024, stdin))
{
    /* do whatever you need with the line that's in buf here */
}

Note your code doesn't know about the file, it just reads from standard input. With <, you tell your environment (CMD on windows, a shell like e.g. bash on *nix) to open that file for you and provide it to your program as the standard input instead of the default, the controlling terminal, which would normally just read from the keyboard.

Hint: 1024 is kind of a random pick, most text files don't have lines exceeding 1kb. You might want to modify it to better suit your expected input.

0

another way to do what you are looking for is

#include <stdio.h>

int main (void) {
  int c;
  while ((c = fgetc(stdin)) != EOF) fputc(c, stdout);
  return 0;
}

some more help here

Community
  • 1
  • 1
asio_guy
  • 3,667
  • 2
  • 19
  • 35
  • 1
    Of course, there are a *lot* of ways to read from a stream. Reading line-by-line just seemed the most natural for me if the expected input is a text file. I think the essence of the question comes down to a lack of understanding what exactly `<` does here. For your answer, I'd suggest to explicitly state this is the variant of reading a single character at a time. –  Sep 19 '15 at 13:02
  • enlightened to the core – asio_guy Sep 19 '15 at 13:14