简体   繁体   中英

How do you use input redirection from a file in C?

I'm very beginner-level in coding, C is the only language I have been learning. I've done thorough research on input redirection to a file to try to figure out how it works, but I do not understand where to use the command or exactly how it is used. My question is, where do I put the redirection command line in the program exactly? I know that it looks something like this: ./a < filename.txt , but I have no idea where to put it in the program, or if it even goes in the program? I want to read data from the files into a scanf using a simple loop. Also, the 'a', is that the exact name of the C program you are writing?

If you want to read from a redirection, then the program needs to read from stdin :

int main(void)
{
    char line[1024];

    fgets(line, sizeof line, stdin);

    puts(line);

    return 0;
}

If you execute the program like this:

$ ./readline

then the user must enter the text and press ENTER .

If you execute the program like this:

$ echo "Hello World" | ./readline
Hello World
$ ./readline < filename
First line of filename

then stdin will be connected to the pipe / redirection. You don't have to worry about this, the shell executing the command does the work (connecting stdin to the pipes, etc) so that your program only need to read from stdin .

Same thing applies for stdout , if you want that the user calls your program and uses the output in a pipe or redirection, then just write normally to stdout . The shell takes care of connecting stdout to the pipe / redirection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM