In: Computer Science
Complete 2a-b
2a) Write a C program which displays the sum of the command
line
arguments. Hint: use sscanf to convert the decimal arguments
(which are strings) to binary numbers that can be added. Use
the file name sum.c for your program. Test your program with
sum 5 -10 3
and
sum 8
and
sum
2b) Write a C program that reads in a file and outputs it
in
reverse order. Use recursion. Test your program with the
file reverse.txt (on our web site). Hint: Structure of
the recursive function reverse that you need:
if not at end of file
read line
save line in a safe area (use strdup to do this)
call reverse
display line that was saved
Use fgets to read line. Recall fgets returns 0 (which
represents
false) on end of file.
1)
#include<stdio.h>
int main(int argc,char*argv[])
{
int a,b,sum;
if(argc!=3)
{
printf("please use "prg_name value1,value2\"\n");
return-1;
}
a=atoi(argv[1]);
b=atoi(argv[2]);
sum=a+b;
printf("sum of %d,%d is:%d\n",a,b,sum);
return 0;}
}
}
2)
#include<stdio.h>
#include<conio.h>
long count_characters(FILE *);
void main()
{
int i;
long cnt;
char ch,ch1;
FILE *fp1,fp2;
if(fp1=fopen("file_1.txt,"r"))
{
printf("the file has been opened....\n);
fp2=fopen("file_2.txt","w"):
cnt=count_characters(fp1);
fseek(fp1,-1L,2);
printf("the number of characters to be copied%d\n",ftell(fp1));
while(cnt)
{
ch=fgetc(fp1);
fputc(ch,fp2)
fseek(fp1,=-2l,L,1);
cnt--;
}
printf("\n**file copied successfully in reverseorder**\n");
}
else
{
perror("error occured\n");
}
fclose(fp1);
fopen(fp2);
}
long count_charcteristics(file*f)
{
fseek(f,-1l,2);
long last_pos=ftell(f);
last_pos++;
return last_pos;
}