Given 2 files \"text.txt\" and \"alpha.txt\". Write a C program that does the fo
ID: 3811875 • Letter: G
Question
Given 2 files "text.txt" and "alpha.txt". Write a C program that does the following.
- Reads the char values in the 'text.txt' file. Contents of 'text.txt' file are: adbb
- Reads their corresponding 2 digit code representation from the 'alpha.txt' file. Contents of 'alpha.txt' file are: a 00 b 01 c 10 d 11
- Does the following conversion (for example): adbb (text from text.txt) --> 00110101 (substituting the corresponding code for adbb) --> 5 (ASCII represention of the 8 bits 00110101)
- Write the result from above (e.g. 5) to a file called 'out.txt'.
Explanation / Answer
#include <stdio.h>
char convertBinaryArrayToint(char binaryCharArray[])
{
char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
total *= 2;
if (*start++ == '1') total += 1;
}
return total;
}
void readAlphaFile(char *fileName, char arr[26][2])
{
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
while ((c = fgetc(file)) != EOF)
{
char d;
d = fgetc(file);
d = fgetc(file);
arr[c-'a'][0] = d;
d = fgetc(file);
arr[c-'a'][1] = d;
fgetc(file);
}
fclose(file);
}
int main()
{
char arr[26][2];
int i;
for(i = 0; i < 26; i++)
{
arr[i][0] = '';
arr[i][1] = '';
}
readAlphaFile("alpha.txt", arr);
char binaryCharArray[1000];
FILE *file = fopen("text.txt", "r");
char c;
i = 0;
while ((c = fgetc(file)) != EOF)
{
binaryCharArray[i++] = arr[c-'a'][0];
binaryCharArray[i++] = arr[c-'a'][1];
}
fclose(file);
binaryCharArray[i] = '';
c = convertBinaryArrayToint(binaryCharArray);
file = fopen("out.txt", "w");
fprintf(file, "%c ", c);
fclose(file);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.