向程序传递一个文件供其读取
Passing a program a file for it to read
我需要 运行 一个程序并将一个文件传递给它。写作时有效
./my_program input.txt
我在使用这种格式时需要它 运行
./my_program < input.txt
但它会引发分段错误。
这不是我的确切代码,但这是我认为最重要的想法。
int main(int argc, char **argv){
FILE *f = fopen(argv[1], "r");
char *input;
input = new char[1000];
if (f == NULL) {
std::cout << "file not found" << std::endl;
}
else {
std::cout << "found file" << std::endl;
}
fread(input, 1000, 1, f);
//...do stuff with it...//
return 0;
}
所以基本上,当它以其他方式正常工作时,我如何绕过“<”抛出分段错误?
你不需要考虑文件。就像用户键入 input.txt 文件的内容一样编写您的代码。
“<”正在将指定文件的内容重定向到您的标准输入。
希望这能解释更多:
http://wiki.bash-hackers.org/howto/redirection_tutorial
我需要 运行 一个程序并将一个文件传递给它。写作时有效
./my_program input.txt
我在使用这种格式时需要它 运行
./my_program < input.txt
但它会引发分段错误。
这不是我的确切代码,但这是我认为最重要的想法。
int main(int argc, char **argv){
FILE *f = fopen(argv[1], "r");
char *input;
input = new char[1000];
if (f == NULL) {
std::cout << "file not found" << std::endl;
}
else {
std::cout << "found file" << std::endl;
}
fread(input, 1000, 1, f);
//...do stuff with it...//
return 0;
}
所以基本上,当它以其他方式正常工作时,我如何绕过“<”抛出分段错误?
你不需要考虑文件。就像用户键入 input.txt 文件的内容一样编写您的代码。
“<”正在将指定文件的内容重定向到您的标准输入。
希望这能解释更多: http://wiki.bash-hackers.org/howto/redirection_tutorial