3

I'm trying to write a program that will read the first character in a text file. If I use ./a.out myfile.txt it works as intended but if I use ./a.out <myfile.txt I get Segmentation fault: 11. The reason why I'm trying to include the <is because this what is in the spec of the assignment. The below code is just a simplified example that i've made that has the same issue:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


int func(int argc, char **argv){
    FILE *fp;
    int test = 0;
    fp = fopen(argv[1], "r");
    fscanf(fp, "%i", &test);
    printf( "current file: %s \n", argv[1]);


}


int main(int argc, char **argv){
    func(argc, argv);   
}

Is there any way I can get it to accept the argument as <myfile.txt?

4

3 回答 3

7

不,你也不应该尝试。以这种方式重定向的文件将出现在stdin,您应该使用它来代替(提示:检查argc)。

于 2013-05-18T02:22:43.667 回答
5

如果要使用指定的文件,但要使用标准输入,请使用以下内容:

if (argc > 1)
    fp = fopen(argv[1], "r");
else
    fp = stdin;
于 2013-05-18T02:53:00.510 回答
2

在您的命令./a.out <myfile中,您将标准输入重定向到myfile. 这意味着从 stdin 读取实际上是从myfile. 所以,在这种情况下,你的argc == 1, 所以argv[1]你用来打开 is NULL(参见main其参数的规范)。fopen使用NULL名称时崩溃。

你可以用另一种方式来做你的实用程序:总是阅读stdin. 当您需要输入文件时,请执行以下操作:cat myfile | ./a.out. 这是非常好的方法,值得考虑。

于 2013-05-18T03:29:08.150 回答