ç如何把多个文件进行论证? [英] C How to take multiple files for arguments?
问题描述
你如何询问用户输入文件作为要使用的参数(多达他们想)?同时你会如何打印到文件?
How would you ask for the user to input files as arguments to be used (as many as they would like)? Also How would you print to a file?
scanf("%s", user_filename);
FILE *fp;
fp = fopen (user_filename, "r");
我曾尝试做不同的事情,但我只能把它取一个文件。
I have tried doing various things to it but I can only get it to take one file.
推荐答案
一些文件名传递给你的C程序中最简单的方法是将它们作为参数传递给你的C程序。
The easiest way to pass some file names to your C program is to pass them as arguments to your C program.
参数传递给使用参数的C程序主
:
Arguments are passed to a C program using the parameters to main
:
int main( int argc, char *argv[] )
{
...
}
值 ARGC
表示多少参数有,和的argv []
是包含字符串指针数组参数。请注意,在指数的第一个参数 0
(字符串由 ARGV指出,[0]
)是命令名本身。传递给该命令的参数其余都在的argv [1]
,的argv [2]
,等
The value argc
indicates how many parameters there are, and argv[]
is an array of string pointers containing the arguments. Note that the first argument at index 0
(the string pointed to by argv[0]
) is the command name itself. The rest of the arguments passed to the command are in argv[1]
, argv[2]
, and so on.
如果您编译程序,并调用它是这样的:
If you compile your program and call it like this:
my_prog foo.txt bar.txt bah.txt
随后的 ARGC
将 4
(请记住,包括命令)值和的argv
值将是:
Then the value of argc
will be 4
(remember it includes the command) and the argv
values will be:
argv[0] points to "my_prog"
argv[1] points to "foo.txt"
argv[2] points to "bar.txt"
argv[3] points to "bah.txt"
在你的程序的话,你只需要检查 ARGC
有多少参数有。如果的argv> 1
,那么至少有一个参数起始的argv [1]
:
In your program then, you only need to check argc
for how many parameters there are. If argv > 1
, then you have at least one parameter starting at argv[1]
:
int main( int argc, char *argv[] )
{
int i;
FILE *fp;
// If there are no command line parameters, complain and exit
//
if ( argc < 2 )
{
fprintf( stderr, "Usage: %s some_file_names\n", argv[0] );
return 1; // This exits the program, but you might choose to continue processing
// the other files.
}
for ( i = 1; i < argc; i++ )
{
if ( (fp = fopen(argv[i], "r")) == NULL )
{
fprintf( stderr, "%s: Gah! I could not open file named %s!\n", argv[0], argv[i] );
return 2;
}
// Do some stuff with file named argv[i], file pointer fp
...
fclose( fp );
}
return 0;
}
这仅仅是几种不同的方式来做到这一点(功能上和风格上),这取决于你需要如何处理的文件之一。
This is just one of several different ways to do it (functionally and stylistically), depending upon how you need to process the files.
这篇关于ç如何把多个文件进行论证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!