jekyll jekyll - 1 month ago 13
C Question

Read from a text file shift cipher in C

I'm working on Shift cipher, I am having problems with encryption. It has no errors or trouble compiling but after I run it the output file is empty. i think reading the file but not encrypted out.txt file is empty. i didn't solve it. Thank you.

#include<stdio.h>
#include<stdlib.h>
#include <ctype.h>

int encode (int, int);

int encode(int ch, int key) {
if (islower(ch)) {
ch = (ch-'a' + key) % 26 + 'a';
ch += (ch < 'a') ? 26 : 0;
}
else if (isupper(ch)) {
ch = (ch-'A' + key) % 26 + 'A';
ch += (ch < 'A') ? 26 : 0;
}
return ch;
}
int main (void)
{
FILE *file_in;
FILE *file_out;
char ch;
int key;

file_in = fopen("/Users/mathmoiselle/Desktop/lucky.txt", "r");


if( file_in == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("\n The contents of the file are : \n");

while( ( ch = fgetc(file_in) ) != EOF )
{
printf("%c",ch);
}

file_out = fopen("/Users/mathmoiselle/Desktop/out.txt","r");

printf("\n Enter the alphabetic offset key you would like to use:");
scanf("%d", &key);

while( ( ch = fgetc(file_in) ) != EOF )
{
printf("%c", ch);
ch=encode(ch, key);
fprintf(file_out, "%c", ch);
}
printf("file has been encoded");
fclose(file_out);
fclose(file_in);

return 0;
}

Answer

Following on from my comments. You need to rewind the file pointer for file_in and also your includes were poorly formatted at the top. Not sure whether this makes a difference (beginner myself, but certainly stuck out when I read it):

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int encode (int, int);

int encode(int ch, int key) {
    if (islower(ch)) {
        ch = (ch-'a' + key) % 26 + 'a';
        ch += (ch < 'a') ? 26 : 0;
    }
    else if (isupper(ch)) {
        ch = (ch-'A' + key) % 26 + 'A';
        ch += (ch < 'A') ? 26 : 0;
    }
    return ch;
}
int main (void)
{
    FILE *file_in;
    FILE *file_out;
    char ch;
    char text[300];
    int key;

    gets(text);
    file_in = fopen("shift_cipher.c", "r");


    if( file_in == NULL )
    {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }
    printf("\n The contents of the file are : \n");

    while( ( ch = fgetc(file_in) ) != EOF )
    {
        printf("%c",ch);
    }

    rewind(file_in);

    // while (fgets(line, MAXLINE, f1)) {
    //     printf("%s", line);
    // }

    gets(text);
    file_out = fopen("out.txt","w");

    printf("\n Enter the alphabetic offset key you would like to use:");
    scanf("%d", &key);

    while( ( ch = fgetc(file_in) ) != EOF )
    {
        printf("%c", ch);
        ch=encode(ch, key);
        fprintf(file_out, "%c", ch);
    }
    printf("file has been encoded");
    fclose(file_out);
    fclose(file_in);

    return 0;
}