Archive
Posts Tagged ‘Command line arguments’
C++ Program to implement File Handling with Command Line Arguments – Q31
January 31, 2010
Leave a comment
Q31. Program to implement File Handling with Command Line Arguments:
Copy the contents of an existing file to a new file the names of which are taken as command line arguments. The program should handle errors if the given first file name does not already exist.
… from College notes (BCA/MCA assignments):
#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <string.h>
#include <conio.h>
void main(int argc, char *argv[]){
char src[12], dest[12];
char buff[1000];
int len;
clrscr();
if(argc > 3){
cout<<"\n Illegal Number of Arguments."<<endl;
exit(1);
}
else if(argc == 2){
cout<<"\n Enter the Destination File."<<endl;
cin>>dest;
}
else if(argc == 1){
cout<<"\n Enter Source and Destination File."<<endl;
cin>>src;
cin>>dest;
}
else{
strcpy(src, argv[1]);
strcpy(dest, argv[2]);
}
ifstream fin;
fin.open(src, ios::in);
if(!fin){
cerr<<"\n File Does not Exist.";
getch();
exit(1);
}
fin.read((char*)&buff, sizeof(buff));
fin.close();
len = strlen(buff) - 1;
ofstream fout;
fout.open(dest, ios::out);
fout.write((char*)&buff, len);
fout.close();
cout<<"\n File copied Successfully.";
getch();
}
Output:
C:\TC\MANOJ>31_FH.exe man.txt abc.txt
File Copied Successfully.
Categories: Cpp
Command line arguments, Cpp, Cpp File Handling, File Handling, ifstream, ofstream
C++ Program to check Command Line Arguments – Q4
January 4, 2010
Leave a comment
Q4. Program to check Command line arguments:
Accept an n digit number as command line argument & perform various tasks specified below:
i) Find the sum of digits of the number
ii) Find the reverse of a number
… from College notes (BCA/MCA assignments):
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <math.h>
void Sum_Num(char *);
void Rev_Num(char *);
void main(int argv, char *argc[]){
char patt[10];
clrscr();
if(argv < 1)
cout<<"\n Insuffecient Arguments. \n";
else{
strcpy(patt, argc[1]);
cout<<”\n Argument is: “<<patt;
Sum_Num(patt);
Rev_Num(patt);
}
getch();
}
void Sum_Num(char *pt){
int sum = 0, i = 0;
while(*(pt+i) != '\0'){
sum += int(*(pt+i)) - 48;
i++;
}
cout<<"\n Sum: "<<sum;
}
void Rev_Num(char *pt){
long r_num = 0;
int i = 0;
while(*(pt+i) != '\0'){
r_num += (int(*(pt+i)) - 48) * pow(10, i);
i++;
}
cout<<"\n Reverse: "<<r_num;
}
Output:
Argument is: 12345
Sum: 15
Reverse: 54321




