Unexpected output from C program - c

I'm writing a Caesar which takes in a file and an offset via STDIN, and outputs the encrypted file in STDOUT.
#include <stdio.h>
#include <stdlib.h>
char encrypt(int c, char d) {
if (c>=97&&c<=122) {
c=c-97;
c=c+d;
c=c%26;
c=c+97;
} else if (c>=65&&c<=90) {
c=c-65;
c=c+d;
c=c%26;
c=c+65;
}
return (c);
}
void print_file(FILE* fp, char d) {
char c;
c = getc(fp);
if (c==EOF) {
printf("\n");
exit(EXIT_SUCCESS);
}
c = encrypt(c, d);
printf("%c", c);
print_file(fp, d);
}
int main(int argc, char* argv[]) {
FILE* fp;
fp = fopen(argv[1],"r");
char c;
*argv[2]=*argv[2]+4; // Dunno why this makes it work but okay
print_file(fp, *argv[2]);
return 0;
}
The expected output from inputting a file with offset of 0 should print the contents of said file without any modification. Instead, the output is an offset of -4, making the input of 4 outputting the offset of 0. Moreover, any negative integer will output a fixed offset of -7.
I've added a a line of code to fix this issue, indicated by my comment. With this, the program works with positive integers, while any negative integer outputs with a fixed offset of -4.
I've tried isolating the individual functions. I cannot get this to reproduce.

Related

Using fscanf to store words from file in an array

I am trying to write a program for some classwork that reads in a file using fscanf, and then stores each word into an array with one word in each element. Then I need to print each element of the array out on to a new line on the console.
The getty.txt file has the Gettysburg address in it with appropriate spacing, punctuation, and is multiline.
What I think is happening is that the entire text is being stored in the first element of the array, but I am not 100% sure as I am still learning to debug and write in C.
Any advice as to what I am doing wrong would be great! I currently only seem to be getting the last word and some extra characters.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void readFile();
void writeFile(char* buffer, int bufferlen);
FILE *fpread;
FILE *fpwrite;
char filebuffer[1000];
int filebufferlen = 0;
int main(int argc, char *argv[]) {
fpwrite = fopen("csis.txt", "w");
readFile();
writeFile(filebuffer, filebufferlen);
fclose(fpwrite);
return 0;
}
void readFile() {
char c;
filebufferlen = 0;
if(!(fpread = fopen("getty.txt", "r"))){
printf("File %s could not be opened. \n", "getty.txt");
fprintf(fpwrite,"File %s could not be opened. \n", "getty.txt");
exit(1);
}
while (!feof(fpread)) {
fscanf(fpread, "%s", filebuffer);
filebufferlen++;
}
}
void writeFile(char* filebuffer, int filebufferlen) {
for (int i = 0; i < filebufferlen; ++i){
printf("%c\n", filebuffer[i]);
}
}
After fixing the compile problems:
the code does not contain any code nor data declarations to contain an array of 'words.' So naturally, nothing but the last word is actually saved so it can be printed out.

Converting symbols to lowercase letters in c

I'm writing a program that encodes a file using xor and print the encrypted text into another file. It technically works, however the output contains several symbols rather than only lowercase characters. How would I tell the program to only print lowercase letters, and be able to decode it back?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *args[]){
FILE *inFile, *outFile, *keyFile;
int key_count = 0;
int encrypt_byte;
char key[1000];
inFile = fopen("input.txt", "r");
outFile = fopen("output.txt", "w");
keyFile = fopen("key.txt", "r");
while((encrypt_byte = fgetc(inFile)) !=EOF)
{
fputc(encrypt_byte ^ key[key_count], outFile); //XORs
key_count++;
if(key_count == strlen(key)) //Reset the counter
key_count = 0;
}
printf("Complete!");
fclose(inFile);
fclose(outFile);
fclose(keyFile);
return(0);
}
Here is the output I get:
ÕââÐå朶è”ó
I just want it to only use lowercase letters
You can't. You either XOR all data of the file, or you don't. XOR-ing will result in non-printable characters.
What you can do though, is first XOR it and then encode it base64.
To get your original text/data back, do the reverse.
See also How do I base64 encode (decode) in C?
use the function tolower()
here there is an example:
#include<stdio.h>
#include<ctype.h>
int main()
{
int counter=0;
char mychar;
char str[]="TeSt THis seNTeNce.\n";
while (str[counter])
{
mychar=str[counter];
putchar (tolower(mychar));
counter++;
}
return 0;
}

How to read and compare character 255 in C

I need to write a code that searches all the aparition of a string in a file. Recently, my teacher told me to search string (char)255(char)255 in a file with the same string. The problem is that I can not read those characters and badly, I cannot distinguish or compare those caracter to EOF; My code for searching the given string in a file is :
//problema 14
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char b;
int k=0;
if(argc!=3) {
fprintf(stderr,"Utilizare: %s fisier sir\n",argv[0]);
return 1;
}
if(argv[2][0]=='\0'){
fprintf(stderr, "String vid\n");
return 1;
}
FILE *f;
f=fopen(argv[1],"r");
if (!f)
{
perror(argv[1]);
return 1;
}
int i=0;
while((b = fgetc(f))!=EOF)
{
if(b==argv[2][i]) i++;
else {
fseek(f,-i, SEEK_CUR);
i=0;
}
if(argv[2][i]=='\0'){
k++;
fseek(f,-i+1, SEEK_CUR);
i=0;
}
}
printf("\nSULFUS %d APPEARANCES\n",k);
return EXIT_SUCCESS;
}
what can I do with this code to work on comparint string of (char)255 characters?
The trick is to realize that fgetc returns an int.
So, change the data type of bto int!
But then, "while" does nothing, because it seems that 255 is also recognized as EOF or it goes infinite. I tried also with int but I couldn't figure out much...This teacher is like a compilator, he likes to put you in trouble.

(C) Program doesn't print all values from input file

Working with C.
OK so this is probably something obvious but for some reason my program will only print a certain number of values from a .dat input file as opposed to printing all of them. Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int N = 0;
int j;
float i;
const char Project_Data[] = "FloatValues.dat";
FILE *input = fopen(Project_Data, "r");
if(input != (FILE*) NULL)
{
while(fscanf(input, "%e", &i) == 1)
{
printf("%e\n",i);
++N;
}
printf("\t The number of values in this file is: %d\n", N);
fclose(input);
}
else
printf("Input file could not be read.\n");
return(0);
}
Yeah, so there's about 100000 values or so to be printed yet I only seem to be able to get 20000. The values in the file are ordered sequentially and the compiler only seems to start printing nearer the bottom of the file, after about 80000 or so values.
Anybody know where I'm going wrong?

To generate hexadecimal numbers for 1000 bytes in C

I want to generate hexadecimal numbers in C starting with seed value(initial value) 0706050403020100.My next numbers should be 0f0e0d0c0b0a0908 and so on for next iteration.
In that way i want to generate numbers for say 1000 bytes.
1)how can i generate these hexadecimal numbers.
2)How to store these numbers if i want to compare the generated/produced hexadecimal numbers character by character with the data available in a buffer(dynamic) which has contents of a read file.
Any suggestions/answers are most welcome as i am still learning C language.
EDIT:Here's the code i have tried.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
char *buffer, c;
size_t filesize, result;
int i, expected_data[];
fp = fopen("hex_data", "r");
if (fp == NULL) {
fputs("Error\n", stderr);
exit(1);
}
fseek(fp, 0L, SEEK_END);
filesize = ftell(fp);
printf("Size of hex_data file is:%u \n", filesize);
fseek(fp,0L,SEEK_SET);
buffer = (char*) malloc(sizeof(char)*filesize);
if(buffer == NULL){
fputs("\nMemory error ", stderr);
}
buffer_size = fread(buffer, sizeof(char), size, fp);
for(i=0; i < result; i++) {
printf("%c",*(buffer +i));
}
printf("No of elements read from file are:%u \n", buffer_size);
fseek(fp,0L,SEEK_SET);
int current_pos = 0;
while(current_pos < buffer_size) {
if (buffer[current_pos] != expected_data) {
fputs("Error\n",stderr);
}
else {
current_pos++;
expected_data = next_exp_data(data); //function is call hexadecimal numbers produced
}
}
Here i want to write a function to generate hex numbers for 1000 bytes starting from 0706050403020100.If this is the initial data everytime if i add 08 to each byte i should get the next number(til 1000 bytes).But i don't know how to do it.Can anyone help me out.
Any corrections in the code are most welcome.
This will generate 1000 bytes of random hexadecimal numbers. (Or rather, the ASCII representation of 1000 hexadecimal digits.)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i;
for (i=0; i<1000; i++) {
printf("%x", rand()%16);
}
printf("\n");
return EXIT_SUCCESS;
}
If you wanted to store them in a buffer to compare with something else later, you might want to look at sprintf instead of printf. For that, you really need to understand how strings are allocated and used in C first.
EDIT: This might be more what you're after. It reads hexadecimal digits from standard input (which can be redirected from a file if desired) and checks to see if they follow the pattern that you described.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int expected_number = 7;
unsigned int read_number;
while (1 == scanf("%2x", &read_number)) {
if (expected_number != read_number) {
fprintf(stderr, "Expected %02x but got %02x.\n", expected_number, read_number);
}
expected_number--;
if (expected_number == -1) expected_number = 15;
}
return EXIT_SUCCESS;
}
Your numbers are large, so use a 64-bit unsigned integer data type, such as unsigned long long. You won't be able to deal with numbers greater than 2**64 without adopting a new scheme. Print hex values using printf("%x", value).
You can look at GNU GMP library for arbitrarily large integers.

Resources