Project 1: Compute the frequencies of characters in a given input file. (Ignore
ID: 3742506 • Letter: P
Question
Project 1: Compute the frequencies of characters in a given input file.
(Ignore all tabs, spaces and line returns)
I. Input: a txt file (use argv[])
II. Output: a txt file (use argv[]) with the following format:
(Do not print any charactors that have zero count.)
char1 # count
char2 # count
char3 # count
char4 # count
III. Data structure:
- charIn (char)
- index
- charCounts[256] a 1D array where 256 is max number of different ascii characters.
- printAry
VI. Algorithm for counting
step 0: - open input and output files
- initialize charCounts array to zero.
step 1: charIn <- get the next character from inFile, one character at a time
step 2: index <- cast charIn to integer
step 3: charCounts[index]++
step 4: repeat step 1 to step 3 while infile is not empty
step 5: printArray
step 6: close all files
VII. Algorithm for printArray
step 1: index <--0
step 2: if charCounts[index] > 0
symbol <-- cast index to charactor
write symbol charCounts[index] per text line
step 3: index ++
step 4: repeat step 2 to step 3 while i < 256
Explanation / Answer
Eg: ./a.out /home/user/input.txt /home/user/output/txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int oc, char **argv)
{
int index = 0;
char charIn = 0;
int charCounts[256] = {0};
int i = 0; //for for-loop
FILE *inFile = NULL;
FILE *outFile = NULL;
printf("input file %s ", argv[1]);
printf("output file %s ", argv[2]);
//Read the input File
inFile = fopen(argv[1], "r");
if (inFile == NULL)
{
printf("file open problem ");
}
else
{
fseek(inFile, 0, SEEK_END);
long fSize = ftell(inFile);
fseek(inFile, 0, SEEK_SET);
//read the file in repeat mode to get fetch each characters
while((charIn =fgetc(inFile)) != EOF)
{
//cast character to integer and store in charCounts index
index = (int)charIn;
charCounts[index]++;
}
fclose(inFile);
//open the output file in write mode.. if not existing file then it creates too. "W"
outFile = fopen(argv[2], "w");
if (outFile != NULL)
{
for(i = 1;i <256;i++)
{
//ignoring the file right is character not occured even once
if (charCounts[i] != 0)
{
fprintf(outFile, "char%d # %d ", i, charCounts[i]);
}
}
fclose(outFile);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.