How to convert binary to sentence - c

I've created a simple Program to store and Retrieve the Passwords whenever I want.For example, I have one password which is Pass so its binary will be 01010000011000010111001101110011. I've created a program that will convert it to binary and will store it in the file. The Program is as given Below:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
FILE *fptr;
char wname[100];
char uname[100];
char pass[100];
char str[50];
char bin[7];
int c2n,i,ii;
clrscr();
printf("\nEnter website name: ");
fflush(stdin);
gets(wname);
printf("\nEnter the username: ");
fflush(stdin);
gets(uname);
printf("\nEnter password: ");
fflush(stdin);
gets(pass);
fptr=fopen("DND","a");
printf("Binary of entered string is : ");
fprintf(fptr,"\n");
for(i=0;i<=strlen(wname)-1;i++)
{
c2n=wname[i];
for(ii=7;ii>=0;ii--)
{
bin[ii]=c2n%2;
c2n=c2n/2;
}
for(ii=0;ii<=7;ii++)
{
printf("%d",bin[ii]);
fprintf(fptr,"%d",bin[ii]);
}
}
printf(":");
fprintf(fptr,":");
for(i=0;i<=strlen(uname)-1;i++)
{
c2n=uname[i];
for(ii=7;ii>=0;ii--)
{
bin[ii]=c2n%2;
c2n=c2n/2;
}
for(ii=0;ii<=7;ii++)
{
printf("%d",bin[ii]);
fprintf(fptr,"%d",bin[ii]);
}
}
printf(":");
fprintf(fptr,":");
for(i=0;i<=strlen(pass)-1;i++)
{
c2n=pass[i];
for(ii=7;ii>=0;ii--)
{
bin[ii]=c2n%2;
c2n=c2n/2;
}
for(ii=0;ii<=7;ii++)
{
printf("%d",bin[ii]);
fprintf(fptr,"%d",bin[ii]);
}
}
fclose(fptr);
printf("\n Your website name,user name and password are protected in binary....\nPress any key to close coder......");
getch();
return 0;
}
Now, I want to create Decoder for this.I want a program to convert all the binary to one sentence. For example.
01010000011000010111001101110011=Pass
I have no Idea how to create it.

Here's something that works for me.
#include <stdio.h>
int main(int argc, char** argv)
{
int ch1 = 0;
int ch2 = 0;
int count = 0;
// Pass the binary file to be read from as the first argument.
char* file = argv[1];
FILE* in = fopen(file, "r");
if ( in == NULL )
{
printf("Unable to open file %s\n", file);
return 1;
}
while ( (ch1 = fgetc(in)) != EOF )
{
if ( ch1 == '\n' )
{
// Reset counters.
ch2 = 0;
count = 0;
fputc(ch1, stdout);
}
else if ( ch1 == ':' )
{
// Skip it for computing characters.
fputc(ch1, stdout);
}
else
{
ch2 <<= 1;
if ( ch1 == '1' )
{
ch2 += 1;
}
count++;
if ( count == 8 )
{
fputc(ch2, stdout);
count = 0;
}
}
}
fputc('\n', stdout);
fclose(in);
return 0;
}

I think a good way to do this is to make use of the bitwise operations provided by the language. Check out this bit of code:
#include <stdio.h>
int main(){
char buf = 0;
int bufi = 0;
int bit;
FILE *fp;
fp = fopen("bin", "r");
if (!fp){
printf("%s","input file failed to open\n");
return -1;
}
while ((bit = getc(fp)) != EOF){
if (bit == '0')
bit = 0;
else
bit = 1;
buf = buf | (bit << (7 - bufi));
bufi++;
if (bufi == 8){
printf("%c", buf);
bufi = buf = 0;
int i;
}
}
printf("%s","\n");
return 0;
}
Hope this helps. Also check this out for more about bitwise operations:
http://en.wikipedia.org/wiki/Bitwise_operation

Everything inside your computer is already binary. There is usually no reason to convert the binary to strings. If you want to print in binary format, something simple as this will do:
void putc_bin (char ch)
{
for(uint8_t i=0; i<8; i++)
{
printf("%d", (ch & 0x80) ? '1' : '0');
ch <<= 1;
}
}

Related

How to give access to text file using if statement?

I am trying to give an if statement to check if a particular name is present in text file, then give access to it otherwise give error message.
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("For person details, please enter the person name: \n");
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
int catch, i=0, index=0;
char ch[100];
printf("Enter your Name: ");
if (scanf("%s", )){ // Don't know what to put here?
perror("Error while reading!");
return 0;
}
catch = fgetc(fr);
while(catch != EOF){
ch[index] = catch;
if (ch[index] == ' '){
ch[index] = '\0';
printf("Here is your result: %s\n",ch);
index = 0;
i++;
}
else
index++;
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
Simply the program firstly opens a file and asks for a user input and verifies if the provided content is case-sensitively matched with the file. If so, then it'll let the program access the entire file and display on the screen, to do that, we must use another FILE b/c the old *fp is already manipulated and in case it's reused, it may display wrong data.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("file.txt", "r"); // for verification
FILE *fp1 = fopen("file.txt", "r"); // for future use
char ch[50], str[50];
short int FLAG = 0;
printf("Enter the string: ");
scanf("%s", &str); // asks for input
while (fscanf(fp, "%s", ch) != EOF) {
if (!strcmp(ch, str)) { // checks if a string matches provided by the user
printf("Found! Here's your details...\n\n");
FLAG = 1;
}
}
if (!FLAG == 1) { // no? exits.
printf("Not found, access denied!\n");
return -1;
}
fclose(fp);
int c = fgetc(fp1); // yes? let's go...
while (c != EOF) {
printf("%c", c); // displays containing data
c = fgetc(fp1);
}
fclose(fp1);
return 0;
}
You'll want to add a variable for your scanf output:
char name[100];
if (scanf("%s", name) != -1)
// ...
Then to compare both you'll use strcmp.
#include <string.h>
//...
if (strcmp(ch, name) == 0)
// both are equal
Note that you can access documentation for scanf and strcmp by typing man scanf or man strcmp in your terminal.
int main()
{
printf("For person details, please enter the person name and id card
number: \n");
printf("Enter your Name: ");
char personName[100];
scanf("%s", personName);
printf("Enter your card number: ");
int cardNumber;
if (scanf("%d", &cardNumber)){
printf("no error detected");
}
else{
printf("error while reading");
}
return 0;
}
The fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
printf("For person details, please enter the person name: \n");
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
int catch, i = 0, index = 0;
char ch[100] = { 0 };
if (fr == NULL)
{
perror("Invalid file opening!");
return 1;
}
printf("Enter your Name: ");
fgets(ch, 100, fr);
size_t len = strcspn(ch, "\n");
ch[(len < 100) ? (len) : (99)] = 0; // For file safety checking
if (strlen(ch)) { // Don't know what to put here?
perror("Error while reading!");
return 1;
}
catch = fgetc(fr);
while (catch != EOF) {
ch[index] = catch;
if (ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your result: %s\n", ch);
index = 0;
memset(ch, 0, 100);
i++;
}
else
{
index++;
}
catch = fgetc(fr);
}
fclose(fr);
return 0;
}

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.
int main
{
file_in = fopen("/Users/mathmoiselle/Desktop/lucky.txt", "r");
if( file_in == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
file_out = fopen("/Users/mathmoiselle/Desktop/out.txt","r");
return 0;
}
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); // Removed in question
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); // Removed in question
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;
}

Most common letter on a file (C programming)

I need to create a function that finds the most common letter in a file using C.
Can't figure out my problem, for some reason it always returns [.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char commonestLetter(char* filename);
void main()
{
char str[101], ch;
FILE *fout;
fout = fopen("text.txt", "w");
if (fout == NULL)
{
printf("Can't open file\nIt's probably your fault, worked perfectly on my PC ;)\n");
fclose(fout);
}
printf("Enter string (to be written on file)\n");
gets(str);
fputs(str, fout);
ch = commonestLetter("text.txt");
printf("The most common letter is %c\n", ch);
fclose(fout);
}
char commonestLetter(char* filename)
{
char ch;
int i, count[26];
int max = 0, location;
FILE *f = fopen(filename, "r");
if (f == NULL)
{
printf("file is not open\n");
return;
}
for (i = 0; i < 26; i++)
count[i] = 0;
while ((ch = fgetc(f)) != EOF)
{
if (isalpha(ch))
count[toupper(ch) - 'A']++;
}
for (i = 0; i < 26; i++)
{
if (count[i] >= max)
{
max = count[i];
location = i + 1;
}
}
return location + 'A';
}
Do
location=i;
No need of i+1
As you are doing location+'A';
Suppose the location count[25] has the highest count, so the location becomes 25+1=26.
Now the return will be 26+65=91 which is of '['
The code of yours is slightly modified but the logic of your is kept
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char commonestLetter(char* filename);
int main()
{
char str[101], ch;
FILE *fout;
fout = fopen("text.txt", "w");
if (fout == NULL)
{
printf("Can't open file\nIt's probably your fault, worked perfectly on my PC ;)\n");
return 0;
}
printf("Enter string (to be written on file): ");
fgets(str,sizeof(str),stdin);
fputs(str, fout);
fclose(fout);
ch = commonestLetter("text.txt");
printf("The most common letter is %c\n", ch);
return 0;
}
char commonestLetter(char* filename)
{
char ch;
int i, count[26];
int max = 0, location;
FILE *f = fopen(filename, "r");
if (f == NULL)
{
printf("file is not open\n");
return;
}
memset(&count,0,sizeof(count));
while ((ch = fgetc(f)) != EOF)
{
if (isalpha(ch))
count[toupper(ch) - 'A']++;
}
for (i = 0; i < 26; i++)
{
if (count[i] >= max)
{
max = count[i];
location = i;
}
}
fclose(f);
return location + 'A';
}
Input & Output:
Enter string (to be written on file): Gil this is a testing
The most common letter is I
The problem here is, in your code,
location = i + 1;
location is i+1 at the end, and you're returning location + 'A'; which is (because of your input, probably) (25+1) + 'A' , i.e., 26 + 'A' which is [.

File does not fprint correctly in C?

So here I have a basic program that will write to a specific line in a file by writing the contents of the file into a temporary file where the new line is written and then the contents of that file is then copied back into the starting file.
(Scores) = File
(Sub) = Temp
#include <stdio.h>
#include <conio.h>
#include <string.h>
void insert(void);
int main()
{
insert();
}
void insert(void)
{
FILE *fp,*fc;
int lineNum;
int count=0;
char ch=0;
int edited=0;
int score=0;
fp=fopen("Test 02 Scores.txt","r");
fc=fopen("Sub.txt","w");
if(fp==NULL||fc==NULL)
{
printf("\nError...cannot open/create files");
exit(1);
}
printf("Enter the score");
scanf("%d",&score);
printf("\nEnter Line Number Which You Want 2 edit: ");
scanf("%d",&lineNum);
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
count++;
if(count==lineNum-1 && edited==0)
{
if(lineNum==1)
{
fprintf(fc,"%d\n",score);
}
else
fprintf(fc,"\n%d\n",score);
edited=1;
while( (ch=fgetc(fp))!=EOF )
{
if(ch=='\n')
break;
}
}
else
fprintf(fc,"%d",ch);
}
fclose(fp);
fclose(fc);
if(edited==1)
{
printf("\nLine has been written successfully.");
char ch;
FILE *fs, *ft;
fs = fopen("Sub.txt", "r");
if( fs == NULL )
{
printf("File is not real");
exit(1);
}
ft = fopen("Test 02 Scores.txt", "w");
if( ft == NULL )
{
fclose(fs);
printf("File is not real\n");
exit(1);
}
while( ( ch = fgetc(fs) ) != EOF )
fputc(ch,ft);
printf("\nFile copied\n");
getch();
fclose(fs);
fclose(ft);
}
else
printf("\nLine Not Found");
}
However, a problem has arisen, I started to write this code for use with strings, but since decided to use number values, whenever I try to copy with the integer values the program will not copy anything right, I Know this may be caused by the char to int but I'd rather have more help in assessing where I should change stuff.
The error is in this line
fprintf(fc,"%d",ch)
%d prints ch as an integer, not as a character, you should instead write
fprintf(fc,"%c",ch)
or use fputc()
There are some small issues with your code, here is a working version. I added comments where I changed things.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h> // needed for exit()
void insert(void);
int main()
{
insert();
}
// use fgets to read from keyboard, it is simpler.
int readNumber()
{
char buffer[64] = {0};
fgets(buffer, sizeof(buffer), stdin);
return atoi(buffer);
}
void insert(void)
{
FILE *fp = NULL; // prefer one decl per row
FILE *fc = NULL;
int lineNum = 0;
int count=0;
int ch=0; // should be int ch=0;
int edited=0;
int score=0;
// file names
const char src[] = "Test 02 Scores.txt";
const char dest[] = "Sub.txt";
fp=fopen(src,"r");
if(fp==NULL)
{
perror(src); // use perror() instead for better error msg
exit(EXIT_FAILURE); // there are std constants for exit args
}
fc=fopen(dest,"w");
if(fc==NULL)
{
perror(dest);
exit(EXIT_FAILURE);
}
printf("Enter the score: ");
score = readNumber(); // using fgets to avoid lingering \n in buffer
printf("\nEnter Line Number Which You Want 2 edit: ");
lineNum = readNumber();
while((ch=fgetc(fp))!=EOF) // fgetc returns int so ch should be int
{
if(ch=='\n') // better to have {} here too
{
count++;
}
if(count==lineNum-1 && edited==0)
{
if(lineNum==1)
{
fprintf(fc,"%d\n",score);
}
else // better to { } here too
{
fprintf(fc,"\n%d\n",score);
}
edited=1;
// i guess you want to remove old score
while( (ch=fgetc(fp))!=EOF )
{
if(ch=='\n')
{
break;
}
}
}
else // {} for avoiding future pitfall
{
fputc(ch,fc);
}
}
fclose(fp);
fclose(fc);
if(edited==1)
{
puts("\nLine has been written successfully."); // puts() when u can
int ch = 0; // int
FILE *fs = NULL;
FILE *ft = NULL;
fs = fopen(dest, "r");
if( fs == NULL )
{
perror(dest);
exit(EXIT_FAILURE);
}
ft = fopen(src, "w");
if( ft == NULL )
{
perror(src);
exit(EXIT_FAILURE); // at program exit files will close anyway
}
while( ( ch = fgetc(fs) ) != EOF )
{
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
printf("\nFile copied\n");
getch();
}
else
{
printf("\nLine Not Found");
}
}

(C code) how would I pass my global variables between functions and return them when the main function needs them also?

(C code) how would I pass my global variables between functions and return them when the main function needs them also? I've posted my code below for reference. Of course, I also have a header file with my function prototypes in it as well but they only list variable types inside the closed brackets, not the variable names...
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "myheader.h"
char user_filename[150];
char user_filename2[150];
FILE *fp;
FILE *fp2;
int num_shift;
int main()
{
int choice; // main variables
int option;
char result;
char ch;
int offset;
char character;
int tmp;
option = 0;
num_shift = 0;
strncpy(user_filename, "not set", sizeof("not set"));
strncpy(user_filename2, "not set", sizeof("not set"));
fp = NULL;
fp2 = NULL;
choice = menu(num_shift, user_filename, option); // get user's first selection
while(choice != QUIT) //execute so long as choice is not equal to QUIT
{
switch(choice)
{
case INPUT_FILE:
input(user_filename);
break;
case OUTPUT_FILE:
output();
break;
case NUM_TO_SHIFT:
num_shift = shift(num_shift);
printf ("Shift by %d\n",num_shift);
break;
case ENCODE:
encode(result, ch, num_shift, character);
break;
case QUIT:
quit();
break;
case REVIEW:
review (user_filename);
break;
default:
printf("Oops! An invalid choice slipped through. ");
printf("Please try again.\n");
}
choice = menu(num_shift, user_filename, 0); /* get user's subsequent selections */
}
quit();
}
int menu(int num_shift, char * user_filename, int option)
{
printf("\nText Encoder Service\n\n");
printf("1.\tEnter name of input file (currently '%s')\n", user_filename);
printf("2.\tEnter name of output file (currently '%s')\n", user_filename2);
printf("3.\tEnter number of characters data should be shifted (currently %d)\n", num_shift);
printf("4.\tEncode the text\n");
printf("5.\tReview the text in the input file\n");
printf("\n0.\tQuit\n\n");
printf("Make your selection: \n");
while( (scanf(" %d", &option) != 1) /* non-numeric input */
|| (option < 0) /* number too small */
|| (option > 5)) /* number too large */
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n\n");
printf("Your choice? ");
}
printf("Selecting %d\n\n", option);
return option;
}
int input(char * user_filename)
{
printf("Enter the filename of the file to encode:\n");
printf("(hit the Enter key when done)\n");
scanf("%s", user_filename);
printf("Getting %s\n\n", user_filename);
fp = fopen (user_filename, "r");
if (fp == NULL)
{
printf("\nSorry, I'm unable to open the file (%s) for reading\n", user_filename);
printf("Please try again.\n");
}
else
{
fclose(fp);
}
return INPUT_FILE;
}
int output()
{
printf("Enter the filename of the output file to store encoded information:\n");
printf("(hit the Enter key when done)\n");
scanf("%s", user_filename2);
printf("Opening File for Writing %s\n\n", user_filename2);
fp2 = fopen (user_filename2, "w");
if (fp2 == NULL)
{
printf("\nSorry, I'm unable to open the file (%s) for writing\n", user_filename2);
printf("Please try again.\n");
} else
{
fclose(fp2);
}
//return user_filename;
return INPUT_FILE;
}
int shift(int num_shift)
{
printf("Enter the number of letters to shift for each character: \n");
printf("(hit the Enter key when done)\n");
scanf("%d", &num_shift);
printf("Setting shift value to: %d\n\n", num_shift);
return num_shift;
}
int encode(char result, char ch, int offset, char character2)
{
int character;
printf("starting encoding with offset of %d\n", offset);
fp = fopen(user_filename, "r");
fp2 = fopen(user_filename2, "w+bc");
if ((fp == NULL) || (fp2 == NULL))
{
printf ("File not found\n");
return (0);
}
fseek(fp, 0, SEEK_SET);
printf("staring Encoding from %s to %s at position %ld\n", user_filename, user_filename2, ftell(fp));
int i = 0;
while(character = fgetc(fp))
{
if ( character == EOF)
{
//printf("%c",character);
//fprintf(fp2,"%c",result);
fclose(fp);
fflush(fp2);
fclose(fp2);
return(0);
}
if (isalpha (character))
{
if (character >= 'a' && character <= 'z')
{
result = character - 'a';
result = (result + offset) % 26; // 26 letters in the alphabet
result += 'a';
if (result < 'a')
{
result = 'z' - ('a' - result)+1;
}
} else if (character >= 'A' && character <= 'Z')
{
result = character - 'A';
result = (result + offset) % 26; // 26 letters in the alphabet
result += 'A';
if (result < 'A')
{
result = 'Z' - ('A' - result)+1;
}
}
//printf("(%c)",result);
} else
{
result = character;
//printf("(%x)", result);
}
printf("%c",result);
fprintf(fp2,"%c",result);
}
return 0;
}
void quit()
{
//fclose(fp);
//fclose(fp2);
printf("Quiting...Bye!");
printf("\n");
exit(0);
}
int review(char * user_filename)
{
char character;
fp = fopen(user_filename, "r");
printf("Showing text from %s file\n", user_filename);
printf("----------BEGIN OF TEXT--------------\n");
while(character = fgetc(fp))
{
if ( character == EOF)
{
printf("%c",character);
printf("\n----------END OF TEXT--------------\n");
fclose(fp);
return(0);
}
printf("%c",character);
}
}
You don't need to pass them around as parameters, you can just access them from anywhere (hence global, well as long as you can see the variable).
Any modifications made to those variables are visible to everyone (aside from multithreading issues) so you have no trouble using them in your functions and in main as well.
You do not need to pass global variables because global variables have global scope, that is they can be accessed anywhere. This is VERY BAD programming practice because it may introduce side-effects later in the program when you decide to use the same name for another purpose for example.
See wikipedia for details.

Resources