现在,我有这样的事情......
CMD控制台窗口: C:\ Users \用户名\桌面和GT; wrapfile.txt hello.txt
您好
我怎么会得到这样的东西?
CMD控制台窗口: C:\ Users \用户名\桌面和GT; wrapfile.txt hello.txt hi.txt
你好嗨
使用此代码?
#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.\n");
}
}
答案 0 :(得分:2)
首先,在您的main
声明中,您应该使用int main(int argc, char* argv[])
而不是现在拥有的extern
。在声明argc
变量(这就是argv和argc)时,指定数组大小是没有意义的。最重要的是,您没有使用正确的类型。 integer
为argv
,array of strings
为arrays of chars
(argv
)。所以char
是argv[0]
s。
然后,只需使用argc计数器循环遍历argv数组。 argv[1]
是程序的名称,argv[n]
到#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>\n", 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\n", 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\n", 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.
}
将是您在执行程序时传递给程序的参数。
以下是对其工作原理的一个很好的解释:http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/#command-line
我的2美分。
编辑:这是工作程序的注释版本。
{{1}}
我希望它有所帮助。
答案 1 :(得分:1)
argv [2]将是第二个文件名。
不要忘记检查argc的值以查看是否有足够的参数有效。
更好:使用boost :: program_options。
警告:此代码在Windows系统上不支持unicode,这使其无法移植。请参阅utf8everywhere.org,了解如何使其支持此平台上的所有文件名。