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