关于 c:我怎样才能得到一个多于一个的文本文件?

How would I get more then one text file accepted?

现在,我有这样的事情...

CMD 控制台窗口:
c:\\\\\\\\users\\\\\\\\username\\\\\\\\Desktop> wrapfile.txt hello.txt

你好

我怎么会得到这样的东西?

CMD 控制台窗口:
c:\\\\\\\\users\\\\\\\\username\\\\\\\\Desktop> wrapfile.txt hello.txt hi.txt

你好你好

用这个代码?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <stdlib.h>

int main(int argc[1], char *argv[1])
{
    FILE *fp; // declaring variable
    fp = fopen(argv[1],"rb");
    if (fp != NULL) // checks the return value from fopen
    {
        int i;
        do
        {
            i = fgetc(fp);     // scans the file
            printf("%c",i);
            printf("");
        }
        while(i!=-1);
        fclose(fp);
    }
    else
    {
        printf("Error.\
"
);
    }
}


嗯,首先:在你的 main 声明中,你应该使用 int main(int argc, char* argv[]) 而不是你现在拥有的。在声明 extern 变量时指定数组大小没有意义(这就是 argv 和 argc )。最重要的是,您没有使用正确的类型。 argcintegerargvarray of strings(它们是 arrays of chars)。所以 argvchars.

数组的数组

然后,只需使用 argc 计数器循环遍历 argv 数组。 argv[0] 是程序的名称,argv[1]argv[n] 将是您在执行程序时传递给程序的参数。

这里有一个关于它是如何工作的很好的解释:http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/#command-line

我的 2 美分。

编辑:这是工作程序的注释版本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fp;
    char c;
    if(argc < 3)    // Check that you can safely access to argv[0], argv[1] and argv[2].
    {               // If not, (i.e. if argc is 1 or 2), print usage on stderr.
        fprintf(stderr,"Usage: %s <file> <file>\
"
, argv[0]);
        return 1;   // Then exit.
    }

    fp = fopen(argv[1],"rb");   // Open the first file.
    if (fp == NULL)   // Check for errors.
    {
        printf("Error: cannot open file %s\
"
, argv[1]);
        return 1;
    }

    do   // Read it.
    {
        c = fgetc(fp); // scans the file
        if(c != -1)
            printf("%c", c);
    } while(c != -1);
    fclose(fp);   // Close it.

    fp = fopen(argv[2],"rb");   // Open the second file.
    if (fp == NULL)   // Check for errors.
    {
        printf("Error: cannot open file %s\
"
, argv[2]);
        return 1;
    }

    do   // Read it.
    {
        c = fgetc(fp); // scans the file
        if(c != -1)
            printf("%c", c);
    } while(c!=-1);
    fclose(fp);   // Close it.

    return 0;       // You use int main and not void main, so you MUST return a value.
}

希望能帮到你。


argv[2] 将是第二个文件名。

不要忘记检查 argc 的值,看看是否有足够的参数有效。

更好:使用 boost::program_options.

注意:此代码在 Windows 系统上不支持 unicode,因此不可移植。请参阅 utf8everywhere.org 了解如何使其支持该平台上的所有文件名。