Write a regular C program that takes four command line arguments: start, stop, s
ID: 3678855 • Letter: W
Question
Write a regular C program that takes four command line arguments: start, stop, step, and file. The first three arguments are nonnegative integers and the fourth is a string. The program is to write numbers to the file specified in the file argument, starting with start, increment by step each time, all the way through stop. Write the numbers ten per line in the file.
Sample Run:
Command Prompt$ ./a.out 0 999 20 file.txt
Should produce a file.txt like:
0 20 40 60 80 100 120 140 160 180
200 220 240 260 280 300 320 340 360 380
400 420 440 460 480 500 520 540 560 580
600 620 640 660 680 700 720 740 760 780
800 820 840 860 880 900 920 940 960 980
Explanation / Answer
#include<stdio.h>
int main(int argc,char *argv[])
{
int start,stop,step;
if(argc==5)
{
start=atoi(argv[1]);// atoi is to convert string to integer
stop=atoi(argv[2]);
step=atoi(argv[3]);
char *filename=argv[4];
FILE *fp;//filepointer
fp=fopen(filename,"w");//opening file with given file name in write mode
int counter=0;
while(start<=stop)
{
char val[10];
sprintf(val,"%d",start);
fprintf(fp,val,"");
fprintf(fp," ");
counter++;
if(counter==10)
{
counter=0;
fprintf(fp," ");
}
printf("%d ",start);
start=start+step;
}
fclose(fp);
}
else
{
printf("Arguments given are not correct");
}
}
if any doubt please comment below.......
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.