命令行中<、>对参数的影响及重定向文件的使用方法
命令行重定向与参数问题解答
一、<和>的作用
这两个符号是shell命令行重定向符,由操作系统的shell(比如bash)提前处理,不会作为参数传递给程序:
<:输入重定向。将指定文件的内容作为程序的标准输入(stdin),替代默认的键盘输入。>:输出重定向。将程序的标准输出(stdout)内容写入指定文件,替代默认的终端打印。
二、file.txt的去向与使用方式
当你执行./a.out hello world <file.txt时,file.txt并没有被当作命令行参数传给程序,而是被shell用来替换程序的标准输入源。此时程序可以直接通过标准输入读取该文件的内容,无需手动打开文件。
比如修改你的测试程序,添加读取标准输入的逻辑:
#include <iostream> #include <string> int main(int argc, char* argv[]) { std::cout << "There are " << argc << " arguments:\n"; for (int count{ 0 }; count < argc; ++count) { std::cout << count << ' ' << argv[count] << '\n'; } // 读取重定向文件的内容 std::cout << "\nContent from redirected file:\n"; std::string line; while (std::getline(std::cin, line)) { std::cout << line << '\n'; } return 0; }
编译后执行./a.out hello world <file.txt,程序会先输出3个命令行参数,接着打印file.txt里的所有内容。
如果是用./a.out hello world file.txt的方式,file.txt是命令行参数,你需要在程序中用文件流手动打开并读取:
#include <iostream> #include <fstream> #include <string> int main(int argc, char* argv[]) { std::cout << "There are " << argc << " arguments:\n"; for (int count{ 0 }; count < argc; ++count) { std::cout << count << ' ' << argv[count] << '\n'; } // 处理作为参数传入的文件 if (argc >= 4) { std::cout << "\nContent from argument file:\n"; std::ifstream file(argv[3]); std::string line; while (std::getline(file, line)) { std::cout << line << '\n'; } } return 0; }
内容的提问来源于stack exchange,提问作者Kevin Truong
相关产品推荐
相关产品推荐

