How can I read a file that contains numbers only, but read it by three digits at a time? I have a long string of numbers and every three digits corresponds to a particular number in itself. i.e. a string of 064045154 would need to be read as '064' '045' and '154'. I need to then subtract one from each of these numbers and the new values I need to convert into their ASCII characters and place these in a new file. This is what I have (focusing on the 'Decrypt' function) but all it does is in the new file place a string of the same character repeated over and over a total number of times equal to the number of integers in the numbers file.
Code:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "limits.h"
int Encrypt(char * FILENAME)
{
char NEW_FILENAME[strlen(FILENAME)+4];
FILE *inFile; //Declare inFile
FILE *outFile; //Declare outFile
int dpos;
char *ptr= strrchr(FILENAME, '.');
dpos=(ptr-FILENAME);
strncpy(NEW_FILENAME, FILENAME, dpos);
NEW_FILENAME[dpos] = '\0';
strcat(NEW_FILENAME, ".enc");
int Byte;
char newByte;
inFile = fopen(FILENAME,"rb");
outFile = fopen(NEW_FILENAME, "w");
if(inFile == NULL || outFile == NULL)
{
printf("Error in opening file");
return 1;
}
else
{
printf("\nFile Opened, Encrypting");
while ( !feof( inFile ) )
{
Byte=fgetc(inFile);
newByte=Byte+1;
if(newByte<100)
{
fprintf(outFile,"0%d",newByte);
}
else
{
fprintf(outFile,"%d",newByte);
}
}
fclose(inFile);
fclose(outFile);
}
return 0;
}
int Decrypt(char * FILENAME)
{
char NEW_FILENAME[strlen(FILENAME)];
FILE *inFile; //Declare inFile
FILE *outFile; //Declare outFile
int dpos;
char *ptr=strrchr(FILENAME, '.');
dpos=(ptr-FILENAME);
strncpy(NEW_FILENAME, FILENAME, dpos);
NEW_FILENAME[dpos] = '\0';
strcat(NEW_FILENAME, ".dec");
inFile = fopen(FILENAME,"rb");
outFile = fopen(NEW_FILENAME, "w");
int newByte;
int Byte;
if(inFile == NULL || outFile == NULL)
{
printf("Error in opening file");
return 1;
}
else
{
printf("\nFile Opened, Decrypting");
}
while (Byte=fgetc(inFile) != EOF)
{
char Count[4];
int i;
while (i=0, i<3, i++)
{
Count[i]=fgetc(inFile);
}
int b=atoi(Count);
newByte=b-1;
fprintf(outFile,"%c", newByte);
}
fclose(inFile);
fclose(outFile);
return 0;
}
int main(int argc, char*argv[])
{
if(strcmp(argv[1], "-e") == 0)
{
char *file_to_be_enc=argv[2];
Encrypt(file_to_be_enc);
}
else if(strcmp(argv[1], "-d") == 0)
{
char *file_to_be_dec=argv[2];
Decrypt(file_to_be_dec);
}
return 0;
}