#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *inputFile;
FILE *outputFile;
int encodeBinary[4] = {0x00, 0x01, 0x02, 0x03};
char encodeChars[4] = {':', '@', '\n', ' '};
void encode(const char * inFile, const char * outFile)
{
inputFile = fopen(inFile, "r");
outputFile = fopen(outFile, "w");
char lineBuffer[BUFSIZ];
if(inputFile == NULL)
{
perror("Error while opening file.\n");
exit(EXIT_FAILURE);
}
while(fgets(lineBuffer, sizeof(lineBuffer), inputFile))
{
for(int i = 0; lineBuffer[i] != 0; i++)
{
if(lineBuffer[i] == encodeChars[0])
{
fprintf(outputFile, "%d", encodeBinary[0]);
}
else if(lineBuffer[i] == encodeChars[1])
{
fprintf(outputFile, "%d", encodeBinary[1]);
}
else if(lineBuffer[i] == encodeChars[2])
{
fprintf(outputFile, "%d", encodeBinary[2]);
}
else if(lineBuffer[i] == encodeChars[3])
{
fprintf(outputFile, "%d", encodeBinary[3]);
}
}
}
fclose(inputFile);
fclose(outputFile);
}
void decode(const char * inFile, const char * outFile)
{
inputFile = fopen(inFile, "r");
outputFile = fopen(outFile, "w");
char lineBuffer[BUFSIZ];
if(inputFile == NULL)
{
perror("Error while opening file.\n");
exit(EXIT_FAILURE);
}
while(fgets(lineBuffer, sizeof(lineBuffer), inputFile))
{
for(int i = 0; lineBuffer[i] != 0; i++)
{
if(lineBuffer[i] == '0')
{
fprintf(outputFile, "%c", encodeChars[0]);
}
else if(lineBuffer[i] == '1')
{
fprintf(outputFile, "%c", encodeChars[1]);
}
else if(lineBuffer[i] == '2')
{
fprintf(outputFile, "%c", encodeChars[2]);
}
else if(lineBuffer[i] == '3')
{
fprintf(outputFile, "%c", encodeChars[3]);
}
}
}
fclose(inputFile);
fclose(outputFile);
}
void commands(const char * command, const char * inputFile, const char * outputFile)
{
if(strcmp(command, "encode") == 0)
{
encode(inputFile, outputFile);
}
else if(strcmp(command, "decode") == 0)
{
decode(inputFile, outputFile);
}
}
void testValues(int argc, const char * argv[])
{
if(argc == 4)
{
commands(argv[1], argv[2], argv[3]);
}
else
printf("USAGE: ./encode [input_file] [output_file]\n");
}
//MAIN
int main(int argc, const char * argv[])
{
testValues(argc, argv);
return 0;
}
Hi there. I have this piece of code. The code is supposed to get a text file in consisting of the characters : @ "newline" and "space". These characters are then supposed to be converted to binary, 0, 1, 10, 11. After that I also need a way to decode back to the original characters. What I can't seem to figure out is how to be able to read difference between the numbers, if there is 001, how can I know that we are talking about 0, 01, and not 00, 1. I read somewhere that you can use bitwise operations to do this? Any help appreciated!
So, I have change my code a bit. Now the problem is that when I store the values the file that is encoded is as large as the file that is to be encoded. How can I store the values in a file in such a way that it stores the values as hexadecimal (or binary) so that the encoded file is smaller than the original file?