我需要从终端获取文件,我知道命令看起来像这样:
./a.out < fileName.txt
我不确定如何在我的程序中使用fgets()来使用从终端请求的文件。
我需要从终端获取文件,我知道命令看起来像这样:
./a.out < fileName.txt
我不确定如何在我的程序中使用fgets()来使用从终端请求的文件。
使用重定向将输入文件的内容发送到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.) 你关闭标准输入(stdin),然后给它分配一个不同的文件处理器。 2.) 使用dup2函数,将stdin替换为任何其他文件处理器即可实现。
简短回答
一个虚拟例子
#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
你可以使用 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;
}
stdin
读取而不关闭它。 - Barmar