Create a program that filters the data in a CSV file of product data based on some search word and prints the resulting output to a new file. Additionally, the program will print the number of items filtered to stdout. • Your program should take three arguments: an input file to process, an output file to save the results, and a search word. • If the output file already exists or cannot be opened, warn the user by printing "CANNOT OPEN FILE." to stdout. • If a raw CSV line in the input file contains the word given by the user, that raw line must be copied to the new file AS IS. • Print the number of items found to stdout using the format string "%d item(s) returned.\n" • Save your code as prob4.c.
Example Run
$ ./a.out prices.csv filter.csv Intel
4 item(s) returned.
Please find the requested program below. Also including the screenshot of sample output and screenshot of code to understand the indentation. Also please see the screenshot of inputfile used for testing and corresponding output file generated.
Please provide your feedback
Thanks and Happy learning!
Input file:
Ouput File created for searching the pattern 'file'
#include<stdio.h>
#include<string.h>
int ProcessFiles(const char* inputFileName, const char* outputFileName, const char* searchString)
{
FILE * fpIn;
FILE * fpOut;
const int bufferLength = 255;
char inputBuffer[bufferLength];
int matchCount = 0;
size_t dataLen = 0;
//Open Input file
if ((fpIn = fopen(inputFileName, "r")) == NULL)
{
printf("CANNOT OPEN INPUT FILE.\n");
return 0;
}
if ((fpOut = fopen(outputFileName, "w")) == NULL)
{
printf("CANNOT OPEN OUTPUT FILE.\n");
return 0;
}
//Read from the input file line by line
while (fgets(inputBuffer, bufferLength, fpIn))
{
const char* ptr = strstr(inputBuffer, searchString);
if (ptr != NULL)
{
//Found the search string in the current line
++matchCount;
dataLen = strlen(inputBuffer);
//Write the data to the output file
if (fwrite((void*)inputBuffer, sizeof(char), dataLen, fpOut) < dataLen)
{
printf("Error while writing to the output file.\n");
fclose(fpOut);
fclose(fpIn);
return matchCount;
}
}
}
fclose(fpOut);
fclose(fpIn);
return matchCount;
}
int main(int argc, char* argv[])
{
int matchedLinesCount = 0;
if (argc != 4)
{
printf("Invalid number of arguments %d. Usage: %s inputFileName outputFileName searchString\n", argc, argv[0]);
return -1;
}
matchedLinesCount = ProcessFiles(argv[1], argv[2], argv[3]);
printf("%d item(s) returned.\n", matchedLinesCount);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.