I'm trying to go through a file line by line (each line is no more than 50 characters), shift each character by 10 or -10 (to encrypt and decrypt) and then print the shifted string where the old string was. But I'm getting some really funny output.
heres the code:
#include <stdio.h>
int main(void){
FILE *fp;
fp=fopen("tester.csv","r+");
Encrypt(fp); // I call decrypt here when I test it.
fclose(fp);
}
int Encrypt(FILE *fp){
int offset=10;
Shift(fp, offset);
}
int Decrypt(FILE *fp){
int offset= -10;
Shift(fp, offset);
}
int Shift(FILE *fp, int offset){
char line[50],tmp[50], character;
long position;
int i;
position = ftell(fp);
while(fgets(line,50,fp) != NULL){
for(i=0;i<50;i++){
character = line[i];
character = (character+offset)%256;
tmp[i] = character;
}
fseek(fp,position,SEEK_SET);
fputs(tmp, fp);
position = ftell(fp);
}
}
so if tester.csv originally reads
this, is, a, test
running the program produces
~rs}6*s}6*k6*~o}~
êñv[ ‰
this, is, a, test
fputs(tmp, fp);
fputs
writes the bytes until the terminating 0 byte.
while(fgets(line,50,fp) != NULL){
for(i=0;i<50;i++){
character = line[i];
character += offset;
tmp[i] = character;
}
you shift 50 char
s, regardless of how long the line that you read in was, and thus most of the time, there is no 0-byte in the tmp
buffer, thus fputs
often writes at least 50 bytes, some of which have nothing to do with what was in the file at that place, and beyond the buffer, which invokes undefined behaviour and might cause a crash.
You should check for the terminating 0-byte in the loop, probably even stopping at the newline is a good idea.
while(fgets(line,50,fp) != NULL){
for(i = 0; i < 50 && line[i] != 0 && line[i] != '\n'; i++){
character = line[i];
character += offset;
tmp[i] = character;
}
Note: the loop body would simpler be line[i] += offset;
.