How to use redirection in C for file input

2019-01-24 05:03发布

I need to get the file from the terminal, I know the command will look like:

./a.out < fileName.txt

I'm not sure how to use fgets() in my program to use the file requested from the terminal.

3条回答
叼着烟拽天下
2楼-- · 2019-01-24 05:18

Using redirection sends the contents of the input file to stdin, so you need to read from stdin inside your code, so something like (error checking omitted for clarity)

#include <stdio.h>

#define BUFFERSIZE 100

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    fgets(buffer, BUFFERSIZE , stdin);
    printf("Read: %s", buffer);
    return 0;
}
查看更多
淡お忘
3楼-- · 2019-01-24 05:25

1.) you close stdin then assign a different file handler to it 2.) replace stdin with any other file handler using dup2 function you can achieve it

查看更多
叛逆
4楼-- · 2019-01-24 05:41

You dont use fgets, you use gets

The redirection means just that, your terminal input will be the file contents. But your program does not know where it comes from, because it is done by the OS.

查看更多
登录 后发表回答