Write a program that takes a file containing integers and adds an integer to eac
ID: 3622310 • Letter: W
Question
Write a program that takes a file containing integers and adds an integer to each of them. The program takes two input arguments, the name of the file containing the integers and the integer to be added. It then overwrites the integers in the file with the specied integer added to each of the integers in the file. You can assume that the input file contains at most 100 integers, one in each line, and hence use an array to hold them.
A sample input file, numbers.txt is shown below.
3
-5
0
25
-101
If the integer 2 is to be added to each of them, the program is called as:
(~)$ a.out numbers.txt 2
(~)$
The program adds 2 to the numbers 3, -5, 0, 25, -101, which hence become 5, -3, 2, 27, -99, and writes them to numbers.txt, which is therefore as shown below.
5
-3
2
27
-99
Another sample run of the program a.out is shown below. The grayed out text are comments.
(~)$ more numbers2.txt
(numbers2.txt has threee numbers -3, 4, 55, one on each line)
-3
4
55
(~)$ a.out numbers2.txt -5
(Adds -5 to the numbers in more numbers.txt. No output on screen.)
(~)$ more numbers2.txt
(now numbers2.txt has threee numbers -8, -1, 50, one on each line)
-8
-1
50
(~)$
Pseudocode:
Open input file
Loop until end of file:
-Read all numbers from the input file, and saves to an array
Close input file
Open output file(same name as input file)
Loop same number of times as above
-Add the number specified on the command line
-Write the new number to the output file
Close the output file
Explanation / Answer
please rate - thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char * argv[])
{int i,num[100],inc,count;
FILE *io;
io= fopen( argv[1],"r");
if(io== NULL)
{ printf("Error opening input file! ");
return 0;
}
count=0;
while(fscanf(io,"%d",&num[count])>0)
{count++;
}
fclose(io);
clearerr (io);
io== fopen( argv[1],"w");
inc=atoi(argv[2]);
for(i=0;i<count;i++)
{num[i]+=inc;
fprintf(io,"%d ",num[i]);
}
fclose(io);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.