Write a C program that reads data from a file and writes the valid data to a new
ID: 673680 • Letter: W
Question
Write a C program that reads data from a file and writes the valid data to a new file. The original file consists of integer data. However, we only want to keep integer values within a certain range. The name of the original data file, the new file where the valid data should be written, as well as the minimum and maximum value for valid data to be moved into the new file are all obtained from the command line, as is shown below.
You can assume valid input and use of this program. Specifically, you can assume that:
• the user will enter command line arguments in the proper order • the original data file will always exist
• the original data file contains nothing but legal integers
• the user will enter a valid integer for minimum and maximum
• the value entered for minimum will be less than or equal to that for maximum As an example, if the file data.txt contained the following numbers
and you ran your program with the command
./a.out data.txt 20 100 valid.txt
then, after execution, the file valid.txt should contain
When generating your output file, please put each number on a separate line.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *ipfile, *opfile;
int minValue, maxValue, temp;
minValue = atoi(argv[2]); /*Convert the character string to integer minValue*/
maxValue = atoi(argv[3]); /*Convert the character string to integer maxValue*/
ipfile = fopen(argv[1], "r"); /*Open the file for reading.*/
opfile = fopen(argv[4], "w"); /*Open the file for writing.*/
while(!feof(ipfile)) /*As long as there are values in the file.*/
{
fscanf(ipfile, "%i", &temp); /*Read from ipfile into temp.*/
if(temp >= minValue && temp <= maxValue) /*If that temp value is within the valid range.*/
fprintf(opfile, "%i ", temp); /*Write it to the opfile.*/
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.