HOWTO: Open Files Using Command Line ArgumentsLast reviewed: August 26, 1997Article ID: Q39216 |
The information in this article applies to:
SUMMARYIn 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:
MORE INFORMATIONThe 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 <stdio.h> void main (int argc, char *argv[]) { FILE *in, *out; if (argc < 3) /* Enough arguments? */ { puts("Usage: demo infile outfile"); exit(1); } printf("%s\n", argv[0]); printf("%s\n", argv[1]); printf("%s\n", argv[2]); in = fopen (argv[1],"r"); out = fopen (argv[2],"w"); if (in == NULL || out == NULL) { puts("Could not open both files"); exit(2); } puts("Opened both files OK"); exit(0); }The command line: "C:\>demo infile outfile" produces the following output if infile and outfile can be opened:
C:\demo.exe infile outfile Opened both files OK Keywords : CLngIss 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 |
================================================================================
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |