Microsoft KB Archive/39216

{| = HOWTO: Open Files Using Command Line Arguments =
 * width="100%"|

Article ID: Q39216

The information in this article applies to:
 * Microsoft C for MS-DOS, versions 5.1, 6.0, 6.0a, 6.0ax
 * Microsoft C/C++ for MS-DOS, version 7.0
 * Microsoft Visual C++ for Windows, versions 1.0, 1.5, 1.51, 1.52
 * Microsoft Visual C++, 32-bit Edition, versions 1.0, 2.0, 2.1, 4.0, 5.0

SUMMARY
In Microsoft C, filenames may be specified as command line arguments to a C program. The example below uses the first command line argument as the name of the input file and the second as the name of the output file. The parameter argv, which is declared by main, is used to access the command line arguments.

In the example below, the following occurs:

1. argv[0] will contain the full path and name of the source (exe) file.

2. argv[1] will contain the first argument, which is the input filename.

3. argv[2] will contain the second argument, which is the output filename.

MORE INFORMATION
The following program opens a file for reading and writing and also prints argv[0], argv[1], and argv[2]. Note that argc is checked to make sure that two argument strings were actually passed and that the file pointers are checked to make sure that the files were actually opened.

#include 

void main (int argc, char *argv[]) {    FILE *in, *out;

if (argc < 3)          /* Enough arguments? */     {       puts(&quot;Usage:  demo infile outfile&quot;); exit(1); }

printf(&quot;%s\n&quot;, argv[0]); printf(&quot;%s\n&quot;, argv[1]); printf(&quot;%s\n&quot;, argv[2]);

in = fopen (argv[1],&quot;r&quot;); out = fopen (argv[2],&quot;w&quot;);

if (in == NULL || out == NULL) {      puts(&quot;Could not open both files&quot;); exit(2); }    puts(&quot;Opened both files OK&quot;); exit(0); } The command line: &quot;C:\>demo infile outfile&quot; produces the following output if infile and outfile can be opened: C:\demo.exe infile outfile Opened both files OK Keywords          : kbLangC kbVC Version          : MS-DOS:5.1,6.0,6.00a,6.00ax,7.0;  WINDOWS:1.0,1.5,1.51,1.52; WINDOWS NT:1.0,2.0,2.1,4.0,5.0 Platform         : MS-DOS NT WINDOWS Issue type       : kbhowto
 * }