例1:打开指定路径下的一个文本文件,读取其内容,并将其写入到指定路径下的另一个文件当中。其中,采用argv来传递输入文件路径和输出文件路径。
参考代码如下:
#include "stdafx.h" #include "iostream" #include "fstream" using namespace std; int _tmain(int argc, char* argv[]) { if (argc != 3)//输入参数必须为三个,第一个为test 第二个为输入文件的路径,第三个为输出文件的路径 { cout<<"argument error!"<<endl; cout<<"example: test c:/test.txt d:/testOut.txt"<<endl; system("pause"); exit(-1); } for (int i=0; i<3; i++) { cout<<argv[i]<<endl; } ifstream fileIn; fileIn.open(argv[1], ios::in);//根据用户设定的参数,打开输入文件 if (fileIn.fail())//如果文件打开失败,直接退出 { cout<<"fileIn open error: "<<endl; system("pause"); exit(-1); } ofstream fileOut; fileOut.open(argv[2], ios::out);//根据用户设定的参数,打开(创建)输出文件 if (!fileOut) { cout<<"fileOut open error..."<<endl; system("pause"); exit(-1); } char str[500]; while(!fileIn.eof()) { memset(str, '\0', 500*sizeof(char)); fileIn.getline(str, 500); fileOut<<str<<endl; cout<<str<<endl; } fileIn.close(); fileOut<<"I have learn the usage of argc and argv in main function! Thanks to VitoLee!"<<endl; fileOut.close(); system("pause"); return 0; }
笔者在E:\VCprograms\路径下面,创建了一个名为test的控制台工程,将上述代码进行编译,在工程所在的文件件下,生成了一个名为test.txt的可执行文件。需要注意的是,因为该main函数利用了main函数中的argc,argv,所以,不能直接鼠标双击来启动。而必须采用命令行的方式进行启动。具体步骤为:
(1)电脑屏幕左下角,开始---->运行--->在出现的对话框中输入“cmd”,如下图所示:
(2)回车,出现了一个类似于dos的界面,如下所示:
(3)由于我们生成的test.ext位于E:\VCprograms\test\Debug,故而,输入:“cd E:\VCprograms\test\Debug”,回车,出现如下的界面:
(4)输入“e:”,回车(需要特别提醒的是,e后面有一个冒号!)出现如下界面:
(5)输入test,后输入文件的绝对路径和输出文件的绝对路径,并以空格进行区分。例如,笔者输入的是:“test c:/test.txt d:/result.txt”。(注意:Argc是argument count的简写,也就是参数的个数,很显然,这里的argc=3,而argv显然是一个指针数组,对于笔者的输入而言,argv[0]="test",argv[1]="c:/test.txt",argv[2]="d:/result.txt"。)输入完三个参数之后,回车,如下图所示:
这里,我在程序里面,分别输出了argv[0],argv[1],argv[2],之后,程序按照笔者输入的参数“c:/test.txt”,打开位于c盘下面的test.txt文件,将其内容“It's my first example for argc and argv in main function!”读取出来(当然,你的文件里面,可能并不是这句话。。。),并根据笔者输入的参数“d:/result.txt”,在d盘下面创建一个名为result.txt的文件,并将输入文件中读取的内容写入到result.txt输出文件中。就这样,搞定!