gpt4 book ai didi

c++ - 读取文件而不是将其作为参数传递

转载 作者:行者123 更新时间:2023-11-30 18:52:01 27 4
gpt4 key购买 nike

我有一个可执行程序,它只接受两个参数“文件的打开命令 ./file 和另一个参数”。我想知道如何设置一个命令,使文件读取文件而不将其作为 Linux 上的参数传递。我没有该程序的源代码,但我在互联网上找到了这个 C 代码,我认为它可能是相似的。

#include <stdio.h>

int main ( int argc, char *argv[] )
{
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );

/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
}

最佳答案

您可以将命令放入文件中,然后将该文件通过管道传输到您的程序中。

./my_program.exe < my_commands.txt

操作系统将通过std::cin传递文件。所以当你执行

std::string text_line;
std::getline(std::cin, text_line);

输入将来自“my_commands.txt”或重定向到您的程序的任何文件。

关于c++ - 读取文件而不是将其作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35436289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com