如何在C语言中使用重定向进行文件输入

16

我需要从终端获取文件,我知道命令看起来像这样:

./a.out < fileName.txt

我不确定如何在我的程序中使用fgets()来使用从终端请求的文件。

4个回答

21

使用重定向将输入文件的内容发送到stdin,因此您需要在代码中从stdin读取,类似于以下内容(出于清晰起见省略了错误检查)

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

1

1.) 你关闭标准输入(stdin),然后给它分配一个不同的文件处理器。 2.) 使用dup2函数,将stdin替换为任何其他文件处理器即可实现。


这是错误的。如果你正在重定向输入,你应该从 stdin 读取而不关闭它。 - Barmar

0

简短回答

打开你的文件,然后dup2()你的文件描述符指向标准输入。

一个虚拟例子

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
    int fd;
    char *command[] = {"/usr/bin/sort", NULL};
    if (close(STDIN_FILENO) < 0)
    {
        perror("Error close()");
        exit(EXIT_FAILURE);
    }
    if (fd = open(argv[2], O_RDONLY, S_IWUSR | S_IRUSR) < 0)
    {
        perror("Error open()");
        exit(EXIT_FAILURE);
    }
    if (dup2(fd, STDIN_FILENO) < 0)
    {
        perror("Error dup2()");
        exit(EXIT_FAILURE);
    }
    if (execv(command[0], command) < 0)
    {
        perror("Error execv()");
        exit(EXIT_FAILURE);
    }
    return EXIT_SUCCESS;
}

输出:

$ ./a.out < JohnLennon_Imagine_Lyrics.txt
Above us, only sky
A brotherhood of man
Ah
And no religion, too
And the world will be as one
And the world will live as one
But I'm not the only one
But I'm not the only one
I hope someday you'll join us
I hope someday you'll join us
Imagine all the people
Imagine all the people
Imagine all the people
Imagine no possessions
Imagine there's no countries
Imagine there's no heaven
It isn't hard to do
It's easy if you try
I wonder if you can
Livin' for today
Livin' life in peace
No hell below us
No need for greed or hunger
Nothing to kill or die for
Sharing all the world
You
You
You may say I'm a dreamer
You may say I'm a dreamer

0

你可以使用 fread 函数

#include <stdio.h>
#include <malloc.h>

int main () {
    fseek(stdin, 0, SEEK_END);
    long size = ftell(stdin);
    rewind(stdin);

    char *buffer = (char*) malloc(size);
    fread(buffer, size, 1, stdin);

    printf("Buffer content:\n%s\n", buffer);
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接