简体   繁体   English

获取命令行元素并将其存储到数组中

[英]Getting elements of a command line and storing them into an array

I am trying to implement the Unix command "tar" in C. It will be executed using the command p5a -c archive infile1 infile2 ... infilek where the arguments infile1, infile2, ..., infilek denote the names of the files which must be combined to create the archive. 我正在尝试在C中实现Unix命令“ tar”。它将使用命令p5a -c archive infile1 infile2 ... infilek ,其中infile1,infile2,...,infilek参数表示文件名,其中必须合并以创建存档。 I am having trouble getting the file names from the command line and storing them into an array. 我无法从命令行获取文件名并将其存储到数组中。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

I really should not be spoon-feeding what looks like a homework question, but its been 2 years since I last touched gcc and need some practice. 我确实不应该像喂家庭作业那样随意喂食,但是自从我上次接触gcc并需要一些练习以来已经有两年了。

On one hand, it looks like you are capable of using argc to get the data you want. 一方面,您似乎可以使用argc来获取所需的数据。 The problem is 'how to know' the number of arguments. 问题是“如何知道”参数的数量。 Most people use argv for that. 大多数人为此使用argv。 Just made the following with Visual Studio 2010, 借助Visual Studio 2010进行了以下操作,

#include<stdio.h>
#include<conio.h>

int main(int argv, char *argc[])
{
    int i = 1;
    printf("Your arguments are:\n");
    for (i=0; i<argv; i++)
    {
        printf("%s\n",argc[i]);
    }   
    return 0;
}

And here is some sample output (Win7 command line), 这是一些示例输出(Win7命令行),

C:\...\Debug>C_hello.exe this is a string of input
Your arguments are:
C_hello.exe
this
is
a
string
of
input

C:\...\Debug>

I expect you'll get similar results with gcc in linux as well. 我希望您在Linux中的gcc也会得到类似的结果。

EDIT: Did some searching on the matter. 编辑:对此事做了一些搜索。 Looks like there's a standard linux library for this sort of thing, getopt 看起来有一个标准的linux库来处理这种事情, getopt

See the example on that page. 请参阅该页面上的示例。 Very well explained. 很好解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM