So when I use fgets in this code. the output seems to have an extra character. I"m not very experienced in using fgest so I was wondering if maybe someone would enlighten me as to why i get the extra characters. The are ascii value 11 and 12 one on encryption and the other on decryption respectively. Thanks.
Code:
/*simple encryption and decryption*/
#include <stdio.h>
void Encrypt(FILE *);
void Decrypt (FILE *);
void Show (FILE *);
int main(int argc, char *argv[]){
/*open the name of the file to play with */
FILE *fp;
int i;
char buffer[BUFSIZ];
char *find;
if ( (fp = fopen(argv[1], "w+") ) == NULL){
perror("Error");
getchar();
return 1;
}
fputs("Enter some text to add to the file",stdout);
fputs(" Press [ENTER] twice when done",stdout);
putchar('\n');
/*using gets
while ( (gets(buffer) )!=NULL && buffer[0] !='\0')
fputs(buffer,fp);
*/
while ( ( fgets(buffer, BUFSIZ, stdin) ) != NULL && buffer[0] !='\n'){
fputs(buffer,fp);
}
//take out the '\n' in buffer
if( ( find = strchr(buffer,'\n') ) !=NULL)
*find = '\0';
/* alternative to taking out the '\n'
int j;
j = strcspn(buffer, "\n");
buffer[j] = '\0';
*/
puts("Press enter to Encrypt the file");
getchar();
Encrypt(fp);
puts("This is the file encrypted:");
Show(fp);
puts("press enter to decrypt the file");
getchar();
Decrypt(fp);
puts("This is the original contents of the file:");
Show(fp);
puts("Press enter to close the file");
getchar();
if ( ( fclose(fp) ) != 0)
perror("Error");
puts("File closed successfully!");
getchar();
return 0;
}
/*Encrypt the file simply */
void Encrypt(FILE *file){
rewind(file);
/*go through the file and change all characters to 1 charater after */
int i;
while ( ( i = fgetc(file) )!=EOF ){
i = i + 1;
fseek(file, -1, SEEK_CUR);
fputc(i,file);
//fflush(file);
//fflush not needed if going back to original position in the file
fseek(file, 0, SEEK_CUR);
}
}
void Decrypt(FILE *file){
rewind(file);
/*go through the file and change all characters back from 1 */
rewind(file);
int i;
while ( ( i = fgetc(file) )!=EOF ){
i = i - 1;
fseek(file, -1, SEEK_CUR);
fputc(i,file);
//fflush(file);
/* fflush not needed if going back to the original postion in the file
use one or the other */
fseek(file, 0, SEEK_CUR);
}
}
void Show (FILE *file){
rewind(file);
fprintf(stdout,"Here is the contents of your file:\n");
/*stupid! print out the name of the file in question being manipulated */
int i;
while ( ( i = fgetc(file) )!=EOF )
fputc(i,stdout);
putchar('\n');
}
This is output on a trial run:
Enter some text to add to the file Press [ENTER] twice when done
abcdef1234
Press enter to Encrypt the file
This is the file encrypted:
Here is the contents of your file:
?cdefg2345
press enter to decrypt the file
This is the original contents of the file:
Here is the contents of your file:
abcdef1234?
Press enter to close the file