How output text when decrypting a hex? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i am trying to decrypt the hex string: 0440 04b4 04d0 04d0 04dc 03a0 047c 04dc 04e8 04d0 04b0 03a4
It should once decrypted properly read hello world!
however i cannot get it to output the text. instead i get a list of integers. does anyone have any ideas as to how to fix this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv)
{
char file_name[25];
char c; //Variable to hold current character
int sz; //Length of file therefore size of array
FILE *fp;
FILE *fw;
int flag = 1;
while (flag)
{
printf("enter the name of the file you wish to decrypt\n");
fgets(file_name, sizeof file_name, stdin); //fgets safer than gets, prevents infinite input
printf("Reading: %s.....\n", file_name); //debug print, can remove
strtok(file_name, "\n"); //fgets potentially leaves \n on file name, this removes
fp=fopen(file_name,"rt"); //file is opened
fw = fopen("revertedfile.txt", "w"); //oens write file
if( fp == NULL ) //checks if file empty/doesn't exist
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//Following code finds length of file by seeking, then resets the file point to the start
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
printf("Length of file is: %i\n",sz); // Debug print, can delete
fseek(fp, 0L, SEEK_SET);
int data[sz]; //Init array based on file length
int i = 0; //Counter set to 0
while((c=fgetc(fp))!=EOF) //While haven't reached end of file.
{
int ic = (int)c - 200; //minus 200 to the ascii code
//printf("ASCI Code + 100 = %i\n", ic); //debug print
//Could do bit shift before adding to array, I Guess
data[i] = ic; //Add ASCII code to array at i
data[i] = data[i] >> 2; //Bit shift
//Debug print, shows what's happening
int test = data[i];
printf("%i\n", data[i]);
fprintf(fw, "%i\n", data[i]);
//printf("Added %i to the array at point %d\n", test, i);
i++; //Increment pointer for array
}
fclose(fp); //Always close file
fclose(fw); // closes write file
}
return 0;
}
This is the encryption code
printf("enter name of the file you wish to encrypt\n");
fgets(file_name, sizeof file_name, stdin); //fgets safer than gets, prevents infinite input
printf("Reading: %s.....\n", file_name); //debug print, can remove
strtok(file_name, "\n"); //fgets potentially leaves \n on file name, this removes
fp = fopen(file_name,"rt"); //file is opened
fw = fopen("output.txt", "w"); //oens write file
if( fp == NULL ) //checks if file empty/doesn't exist
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//Following code finds length of file by seeking, then resets the file point to the start
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
printf("Length of file is: %i\n",sz); // Debug print, can delete
fseek(fp, 0L, SEEK_SET);
int data[sz]; //Init array based on file length
int i = 0; //Counter set to 0
while((c=fgetc(fp))!=EOF) //While haven't reached end of file
{
printf("Current char: %c\n",c); //Debug print
int ic = (int)c + 200; //Add 200 to the ascii code
//printf("ASCI Code + 100 = %i\n", ic); //debug print
//Could do bit shift before adding to array, I Guess
data[i] = ic; //Add ASCII code to array at i
data[i] = data[i] << 2; //Bit shift
//Debug print, shows what's happening
int test = data[i];
printf("%04x ", data[i]);
fprintf(fw, "%04x ", data[i]);
//printf("Added %i to the array at point %d\n", test, i);
i++; //Increment pointer for array
}
fclose(fp); //Always close file
fclose(fw); // closes write file
//Debug
int test2 = data[1];
printf("The new file is named output.txt");

If you want to decrypt it, you need to know how it was encrypted (well, that still might not be enough). If you just need to print the character each ASCII code represents, you just need to tell printf that by using %c instead of %i.

Related

Chose random a word from txt file and mark it as chosen in C

I want to randomly extract a word from the text file and mark it as chosen.(I want to add a * at the end of the word)
I can extract the words random but when I want to mark the word as chosen (add '*') the * character is added at the end of the file and not at the end of the chosen word. I don't know why.
Does anyone have an idea?
#include <stdlib.h>
#include<stdio.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
char secret[50];
unsigned long fileLen;
srand(time(NULL));
FILE *fp = fopen("input.txt", "a+");
if( fp == NULL ){
fprintf(stderr, "No such file or directory: %s\n");
return 1;
}
//Get file length
fseek(fp, 0, SEEK_END);
fileLen=ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("fileLen --------->%ld\n", fileLen);
do{
// generate random number between 0 and filesize
unsigned long random = (rand() % fileLen) + 1;
// seek to the random position of file
fseek(fp, random, SEEK_SET);
// get next word in row ;)
printf("Random ------->%ld\n", random);//testing purpose
printf("ftell --------->%ld\n", ftell(fp));
int result = fscanf(fp, "%*s %s", secret);
printf("Chosen word is: %s \n", secret);
int len = strlen(secret);
if(result)
{
fseek(fp, len, SEEK_CUR);
fputc('*', fp); // put a '*' at the end of the word that was chosen
}
if( result != 0 )
break;
} while(1);
fclose(fp);
}
Using fseek to get the length is good, and logically, it stops at the end of the file, the issue is that is stays there (that's why * is in the end), so after using it, you are at the end of the file, use rewind(fp) to return to the beginning of the file after using fseek(fp) to get its length.
Also, read Eugene Sh's comment.

Text is being appended at beginning of file instead of at end of file

I'm having a weird bug where the text I append is being added to the beginning of a file instead of the end of it. This ends up making everything backwards.
CODE:
#include <stdio.h>
#include <stdlib.h>
//Check Values
void checkValues(int numDisks, int raidType, int chunkSize){
while (numDisks < 1 || numDisks > 9){
printf("Number inputed for numDisks is not valid, please enter a new value (1-9).\n");
scanf("%d", &numDisks);
}
while(raidType < 0 || raidType > 1){
printf("Number inputed for raidType is not valid, please enter a new value (0-1).\n");
scanf("%d", &raidType);
}
while(chunkSize < 1 || chunkSize > 512){
printf("Number inputed for chunkSize is not valid, please enter a new value (1-512).\n");
scanf("%d", &chunkSize);
}
}
//CreateFile
void createFile(int numDisks){
char raidName[5];
int counter = 1;
//Create each file
while(counter != numDisks + 1){
sprintf(raidName, "raid%d", counter); //Append counter to string
FILE *out = fopen(raidName, "w");
counter++;
}
}
//Write File
void writeFile(int numDisks, char *buffer, int counter){
char raidName[5];
sprintf(raidName, "raid%d", counter); //Append counter to string
//Write File
FILE *out = fopen(raidName, "a");
fprintf(out, "%s", buffer);
}
//Read and Write Files
void rwFile(const char *fileName, int chunkSize, int numDisks){
char buffer[10000];
int counter = 1;
//Reading File
FILE *in = fopen(fileName, "r");
if(in == NULL) return;
//Create File
createFile(numDisks);
while(fgets(buffer, chunkSize + 1, in) != NULL){
//Reset Counter
if(counter > numDisks){
counter = 1;
}
writeFile(numDisks, buffer, counter);
counter++;
}
}
int main(int argc, const char *argv[]){
//Declarations
const char *fileName = argv[1];
int numDisks = atoi(argv[2]);
int raidType = atoi(argv[3]);
int chunkSize = atoi(argv[4]);
checkValues(numDisks, raidType, chunkSize);
rwFile(fileName, chunkSize, numDisks);
}
raid1.txt:
mmmmiiiieeeeaaaa
What should be written to raid1.txt:
aaaaeeeeiiiimmmm
I have tried using fseek but to no avail. If anybody could help me out or point me in the right direction that would help. This is done in C using bash to compile and run the program. The arguments that are passed are test.txt 4 0 4.
I imagine the problem you are seeing is due to each call to writeFile is opening a fresh handle to the file, writing to it and then just returning. Once you have finished using a file handle you should close it, this will flush the file buffer to the file and free up the handle.
What I think is happening here is you are opening up a fresh handle each time and each of these is only having a small amount of data written to it, so isn't being flushed to disk. You program is then exiting and the OS is cleaning up the stale file handles flushing them to disk. As a guess I imagine it is doing that clean up in reverse order hence the appearance of your file being written backwards.
Update your writeFile to include a close and hopefully that should resolve the issue
FILE *out = fopen(raidName, "a");
fprintf(out, "%s", buffer);
fclose(out);
It might be nicer if you open the file for writing in the loop calling writeFile and pass the handle over, and then you only need to open it and close it once.
Worth adding closes elsewhere, where you have opened files too.
HTH
One more thing I see you are using address of local variables for scanf in check values(k), these are local only and Never going to be reflected in Main()

Issue in reading specific portion of File

I am trying to extract and print a specific portion of text from a file at a given time.I used ftell() and fseek() to achieve this.
#include <stdio.h> //// include required header files
#include <string.h>
int main()
{
FILE *fp = fopen("myt", "w+");
if (fp == NULL) //// test if file has been opened sucessfully
{
printf("Can't open file\n");
return 1; //// return 1 in case of failure
}
char s[80];
printf("\nEnter a few lines of text:\n");
while (strlen(gets(s)) > 0) //user inputs random data
{ //till enter is pressed
fputs(s, fp);
fputs("\n", fp);
}
long int a = ftell(fp);
fputs("this line is supposed to be printed only ", fp);//line to be
// displayed
fputs("\n", fp);
fputs("this line is also to be printed\n",fp); //line to be
//displayed
fputs("\n",fp);
long int b = ftell(fp);
fputs("this is scrap line",fp);
fputs("\n",fp);
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
long int c=b-a; //no of characters to be read
char x[c];
fgets(x, sizeof(x), fp);
printf("%s", x);
fclose(fp);
return 0; //// return 0 in case of success, no one
}
I tried using this approach but the program just prints the first line.The output is as follows:
this line is supposed to be printed only
I want to print both the lines intended to be printed.Please suggest an approach.
I think your intent for the reading portion was
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
long int c=b-a; //no of characters to be read
char x[c+1];
int used = 0;
while(ftell(fp) < b)
{
fgets(x+used, sizeof(x)-used, fp);
used = strlen(x);
}
printf("%s", x);
Notes:
I added +1 to the allocation of your buffer x because fgets adds
null termination.
I'm not 100% sure you don't want fflush(fp) between the writes and the reads.

Displaying portion of text from text file in C

I have a text file and I wanted to extract only a specific part of it at a particular time.For that ,I used ftell() while writing to note the start and end positions and then use fseek() to jump to that particular location.
int main()
{
FILE *fp=fopen("myt","w+");
char s[80];
printf ( "\nEnter a few lines of text:\n" ) ;
while ( strlen ( gets ( s ) ) > 0 ) //user inputs random data
{ //till enter is pressed
fputs ( s, fp ) ;
fputs ( "\n", fp ) ;
}
long int a=ftell(fp);
fputs("this line is supposed to be printed only ",fp);//line to be
// displayed
fputs("\n",fp);
long int b=ftell(fp);
printf("start is %ld",a);
printf("\nend is %ld",b);
printf("here is the data...\n");
rewind(fp);
fseek(fp,a,SEEK_CUR); //move to the starting position of text to be
//displayed
char x[1000];
fgets(x,b-a,SEEK_CUR);
printf("%s",x);
return 1;
}
I tried this but face a unexpected abnormal termination of program.Please guide me as to how correctly implement my task.
You want this:
Comments starting with //// are mine
#include <stdio.h> //// include required header files
#include <string.h>
int main()
{
FILE *fp = fopen("myt", "w+");
if (fp == NULL) //// test if file has been opened sucessfully
{
printf("Can't open file\n");
return 1; //// return 1 in case of failure
}
char s[80];
printf("\nEnter a few lines of text:\n");
while (strlen(gets(s)) > 0) //user inputs random data
{ //till enter is pressed
fputs(s, fp);
fputs("\n", fp);
}
long int a = ftell(fp);
fputs("this line is supposed to be printed only ", fp);//line to be
// displayed
fputs("\n", fp);
long int b = ftell(fp);
printf("start is %ld", a);
printf("\nend is %ld", b);
printf("here is the data...\n");
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
char x[1000];
fgets(x, sizeof(x), fp); //// the usage of fgets was totally wrong
printf("%s", x);
return 0; //// return 0 in case of success, no one
}
Disclaimer: The first part reading the strings using gets is still sloppy, you should never use gets, it's an old deprecated function. Use fgets instead.

fscanf, structs, and using the struct c programming

/*Project 1
Student records
1. Read the file with the records
2. store them
3. sort them
4. output them
ex. input and output (SORTED by student ID
2040003 AAAA BBBBBBBBB ComputerScience 3.45
2040002 AAA CCC ElectricalEngineering 3.01
2040005 AAAAAAAAAAAAAAAAA BBB ComputerScience 3.60
2040002,AAA,CCC,ElectricalEngineering,3.01
2040003,AAAA,BBBBBBBBB,ComputerScience,3.45
2040005,AAAAAAAAAAAAAAAAA,BBB,ComputerScience,3.60
char* name = malloc(256*sizeof(char));
*/
int main()
{
typedef struct StudentRecords
{
int StudentID; //must be of size 7 between 1000000 and 9999999
char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
char *Lastname; //= MALLOC(256*sizeof(char));
char *Department; //= MALLOC(256*sizeof(char));
float GPA; // must be between 0 and 4
} STUDENTRECORDS;
/*
First job is read the file
*/
//set variables
int i=0;
char filecontent, file_name[100];
FILE *fp;
STUDENTRECORDS StudentRecords[300];
STUDENTRECORDS a[300];
int size =0;
printf("Enter directory of file\n"); // instructs user to enter directory of file
gets(file_name); //prompt use
fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()
// here is a check to see if fp is empty and throw an error if so
if (fp == NULL)
{
perror("Could not open file\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); // just prints the file name (file_name) you are prompted for
// here is where the printing of contents actually occurs
while ((filecontent = fgetc(fp)) != EOF) // I think EOF is end of feed here, not 100%
{
printf("%c",filecontent);
}
//I thought this line was to figure out how many lines are in the text, but it isnt working.
while (!feof(fp))
{
read(StudentRecords, i, fp);
i++;
}
//because the while statement isnt working, Ive elected to setting size to 3 in order to continue coding.
size = i = 3;
printf("Size = %d\n", size);
//I thought this essentially put the files contents into
for (i = 0; i < size; ++i)
fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);
for (i = 0; i < size; ++i)
printf("%s", StudentRecords[i]);
//printf("%d %s %s %s %f/n", &StudentRecords[i].StudentID, &StudentRecords[i].Firstname, &StudentRecords[i].Lastname, &StudentRecords[i].Department, &StudentRecords[i].GPA);
for (i = 0; i < size; ++i)
fscanf(fp, "%d %s %s %s %f\n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);
for (i = 0; i < size; ++i)
printf("%s", a[i]);
//printf("%d %s %s %s %f/n", &a[i].StudentID, &a[i].Firstname, &a[i].Lastname, &a[i].Department, &a[i].GPA);
// fclose() must follow an fopen()
fclose(fp);
//printf("%g", &StudentRecords);
// return code
return 0;
}
How do I add information into a struct and print it or use it? This is what
i have so far. I've tried many different things and to no avail. I think the problem is with my initializing my struct for use. I can't get it right. I've tried searching for a solution, but each one is different and don't explain much.
Thanks for any suggestions.
Please find example code for reading content from file and storing it in structure also for this example have only take 5 student data entry(you can change as you wish) And on which criteria you want to do sorting? So i leave sorting on you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ENTRY 5
typedef struct StudentRecords
{
int StudentID; //must be of size 7 between 1000000 and 9999999
char *Firstname; //= MALLOC(256*sizeof(char)); // must be any length and allocate memory dynamically.
char *Lastname; //= MALLOC(256*sizeof(char));
char *Department; //= MALLOC(256*sizeof(char));
float GPA; // must be between 0 and 4
} STUDENTRECORDS;
int main()
{
/*
First job is read the file
*/
//set variables
int i=0;
char filecontent, file_name[100];
FILE *fp;
STUDENTRECORDS StudentRecords[MAX_ENTRY];
for(i=0;i<MAX_ENTRY;i++)
{
StudentRecords[i].Firstname = malloc(sizeof(char)*256);
StudentRecords[i].Lastname = malloc(sizeof(char)*256);
StudentRecords[i].Department = malloc(sizeof(char)*256);
}
printf("Enter directory of file\n"); // instructs user to enter directory of file
gets(file_name); //prompt use
fp = fopen(file_name,"r"); //opens the file "r" is read mode for fopen()
// here is a check to see if fp is empty and throw an error if so
if (fp == NULL)
{
perror("Could not open file\n");
//exit(EXIT_FAILURE);
}
i=0;
while(EOF!=fscanf(fp, "%d %s %s %s %f\n", &StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, &StudentRecords[i].GPA))
{
printf("%d %s %s %s %f\n", StudentRecords[i].StudentID, StudentRecords[i].Firstname, StudentRecords[i].Lastname, StudentRecords[i].Department, StudentRecords[i].GPA);
i++;
}
// fclose() must follow an fopen()
fclose(fp);
return 0;
}
Note: never forgot to free string which allocated by malloc after it's use.
A few comments, and some suggestions:
Was it your lecturer who said to use a linked-list? If so.. you really should do that otherwise you'll lose marks for failing to meet the spec.
EOF is 'End Of File'. feof() tells you if the stream pointer passed to it has hit EOF already.
Your while loop to print the contents is inefficient. Rather than reading every. single. character. in. the. file., you should read the entire file (or at least, large chunks thereof, let's not assume infinite memory), fclose() the stream and then operate on the read-in file.
Also, this sort of exercise lends itself very well to fixed-size record
Omitting error handling, variable declarations, structures and
using some pseudocode:
stat("/path/to/file", &statbuf)
inputfd = fopen("/path/to/file", r);
/* assuming that we only have a small file... */
contents = calloc(statbuf.st_size * sizeof(char));
/* read it all in, in one big chunk */
fread(contents, statbuf.st_size, 1, inputfd);
fclose(inputfd);
/* Now you can operate on it however you like */
bytesleft = statbuf.st_size;
/*
* this might need to go at the top of your block, depends on if you
* have enabled C99
*/
char eachline[MAXLINELENGTH];
int n = 0;
while (bytesleft > 0) {
add_new_list_element(mylist);
bzero(eachline, MAXLINELENTH);
memccpy(&eachline, contents[n], '\n', MAXLINELENGTH);
bytesleft -= sizeof(eachline);
nread = sscanf(start, "USE YOUR FORMAT STRING HERE", [variable list]);
if (nread < 0)
/* handle EOF, remember to make use of errno */
}
call_my_sort_function(mylist);
for (; thiselement != NULL; thiselement = thiselement->next)
print_salient_field_values(thiselement);

Resources