3

I don't really know how to ask this...

Supposed I want to read a file from my function, but I have no idea what will be the filename that I want to read because the filename will be passed in my main function as command line argument (argv[])

so my main looks like :

int main(int argc, char *argv[])

my function will look like:

int get_corners(FILE *input, int size, and so on)

What I've tried in my function:

*input = fopen(argv[1], "r");

but, compiler said it doesn't recognize variable argv

So, can someone please help me understand how to call input file when you are not in main and have to deal with command line parameter?

4

4 回答 4

5

首先你不应该取消引用 a FILE*,结构是不透明的。这意味着您只需传递指针。

其次,您想要的可能是将您从命令行获得的文件名作为函数参数传递给您的函数。在 C 中,变量不会在运行时或编译时从其他函数的范围继承。

像这样的东西

int main(int argc, char* argv[])
{
   if (argc < 2)
     return 1;

   printf("%d corners\n", getCorners(argv[1]));
}


int getCorners(char* file) {
    FILE* input = fopen(file, "r");

    .. do soemthing interesting ...


    return cornerCount;
}
于 2012-11-02T09:40:36.793 回答
1

argv is just a parameter to a function like anything else. Unless you make it global or pass it to "get_corners" it's not visible within that function.

To be honest you're probably better handling that file separately from the "get_corners" work anyway, it would appear to be cleaner. Try having a function to open and manage errors on the file read, then pass it's output to get_corners. Also you'll need to more carefully parse the command line than just casually passing it about. You could look at getopts in *NIX to help you, there are plenty of other libs around to make that task easier.

i.e.

FILE *readfile(filename)
{
    FILE *f = fopen(filename, "r");
    // Do some error checking
    return f;
}

main (int arc, char *argv[])
{
    FILE *myfile;
    myfile = readfile(argv[1]);
    get_corners(myfile, ...);
}
于 2012-11-02T09:39:32.643 回答
0

如果它是get_corners()需要 a的要求FILE *,那么您只需在可用的位置打开文件main()argv并将结果指针传递给函数:

int main(int argc, char *argv[])
{
  if(argc > 1)
  {
    FILE *input = fopen(argv[1], "r");
    if(input != NULL)
    {
      const int corners = get_corners(input);
      fclose(input);
      /* Do something with corners here ... */
    }
  }

  return EXIT_SUCCESS;
}
于 2012-11-02T10:03:33.037 回答
0

如果你写了这一行

*input = fopen(argv[1], "r");

get_corners()函数下,所以你必须知道 argv 不是全局变量。main()它是仅由函数看到的变量

你也必须修复这条线

*input = fopen(argv[1], "r");

经过

input = fopen(argv[1], "r");

并将其直接放在main()函数下,以便查看 argv 参数

于 2012-11-02T09:58:58.803 回答