Encryption code doesn't write back to file - c

I compile the code then run it but it returns "Error in writing encrypted data to file. So I assume the issue is somewhere in fwrite.
But I cannot pinpoint it.
I need some help here if you could explain the problem that would be very helpful thanks a lot
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int encrypt_data(FILE *);
int main(void)
{
FILE *fp;
int return_code;
printf("Please enter the file to be encrypted: ");
char filename[200];
scanf("%s", filename);
fp=fopen(filename,"r");
return_code = encrypt_data(fp);
return 0;
}
int encrypt_data(FILE *disk_fp)
{
int i;
unsigned long int file_size;
int key_length;
char *file_buff = NULL;
char key[] = "12`3-vk0fn";
key_length = strlen(key);
fseek(disk_fp, 0, SEEK_END);
file_size = ftell(disk_fp);
rewind(disk_fp);
file_buff = malloc(file_size);
if( fread(file_buff, file_size, 1, disk_fp) != 1)
{
printf("Error in reading file\n");
return -1;
}
for( i=0; i<file_size; i++)
{
file_buff[i] = file_buff[i] ^ key[i%key_length];
}
rewind(disk_fp);
if( fwrite(file_buff, file_size, 1, disk_fp) != 1)
{
printf("Error in writing encrypted data to file\n");
return -1;
}
free(file_buff);
fclose(disk_fp);
return 0;
}

You are opening file with "r" mode which means readonly. Then you try write something to it. By the way you don't check that you open file without errors and don't close it when fwrite/fread failed.

Related

Debug Assertion Failed! (Not Normal)

Okay so my problem is an assertion failure. What I don't understand is that my program correctly inputs from the file, to the array, then prints to the screen, but still shows this error and I just can't figure it out. There's going to be more to this program so please disregard the unused functions.
My code is as follows:
#include <stdio.h>
#include <stdlib.h>
#define MAX 272
FILE* csis;
void processFile(char line[]);
int cipher();
int main(void) {
char line[MAX];
processFile(line, MAX);
fclose(csis);
return (0);
}
void processFile(char line[]) {
FILE* fp;
int i = 0;
if (!(fp = fopen("congress.txt", "r"))) {
printf("File could not be opened for input.\n");
exit(1);
}
fseek(fp, 0, SEEK_END);
fseek(fp, 0, SEEK_SET);
for (i = 0; i < MAX; ++i) {
fscanf(fp, "%c", &line[i]);
printf("%c", line[i]);
}
fclose(fp);
}
int cipher() {}
It looks like you are closing an unopened file handle, in the future you can initialize your file handles to NULL and then test before closing.
FILE *csis = NULL;
...
if (csis)
fclose(csis);
i think you mean
fscanf(fp, "%s", &line[i]);

Need to encrypt a file I have it all written but error in reading file

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int encrypt_data(FILE *);
int main(void)
{
FILE *fp;
int return_code;
printf("Please enter the file to be encrypted: ");
char filename[200];
fgets(filename, 200, stdin);
fp=fopen("filename","w+");
return_code = encrypt_data(fp);
return 0;
}
int encrypt_data(FILE *disk_fp)
{
int i;
unsigned long int file_size;
int key_length;
char *file_buff = NULL;
char key[] = "12`3-vk0fn";
key_length = strlen(key);
fseek(disk_fp, 0, SEEK_END);
file_size = ftell(disk_fp);
rewind(disk_fp);
file_buff = malloc(file_size);
if( fread(file_buff, file_size, 1, disk_fp) != 1)
{
printf("Error in reading file\n");
return -1;
}
for( i=0; i<file_size; i++)
{
file_buff[i] = file_buff[i] ^ key[i%key_length];
}
rewind(disk_fp);
if( fwrite(file_buff, file_size, 1, disk_fp) != 1)
{
printf("Error in writing encrypted data to file\n");
return -1;
}
free(file_buff);
fclose(disk_fp);
return 0;
}
The file I am trying to encrypt is "encrypt.txt" it is just a sentence of nonsense but when I compile this code and then ./a.out it asks me for the file name i enter encrypt.txt I thought it might just want the name but either way it returns "Error in reading file".
I think my fgets() fopen() is the culprit but I am very very lost in how to fix it.
If you could find the error in the code and then explain why it was messing things up it would help me in the future. Thanks a lot.
Remove double quotes of the filename variable. And put it as
fp=fopen(filename,"w+");
maybe I am wrong but with close inspection I thought you better use
scanf("%s", filename);
Instead of the fgets() function. You are reading text from user and not from file at that moment after all.

Writing to a text file through the CMD window and a C exe?

I was wondering how I can get this code to overwrite a textfile from it's text value to it's ASCII value.
I want it to do something like this:
CMD > c:\users\username\desktop>cA5.exe content.txt
content.txt has "abc" in it and I want the command line to change the "abc" to it's ASCII values. 97... etc. I don't want anything written in the command window, I want it to change in the text file. Is this possible, if so, how could I do it with this existing code?
#include <stdio.h>
#include <stdlib.h>
int main(int argc[1], char *argv[1])
{
FILE *fp; // declaring variable
fp = fopen(argv[1], "rb");
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
Not the best code but very simple.
#include <stdio.h>
#include <stdlib.h>
void convertToAHex(char *data, long int size, FILE *file){
rewind(file);
int i;
for(i = 0; i < size; ++i){
fprintf(file, "%d ", data[i]);
}
}
int main(int argc, char *argv[]){
if(argc != 2){
return EXIT_FAILURE;
}
FILE *file = fopen(argv[1], "r+");
if(file){
char *data;
long int size;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
data = (char *) calloc(size, sizeof(char));
if(data){
fread(data, 1, size, file);
convertToAHex(data, size, file);
free(data);
}
fclose(file);
}
return EXIT_SUCCESS;
}

Copying Binary Files

I'm trying to figure out how to copy binary files from one place to another .exe's. I can't seem to find any solutions to learn.
I'm using Windows. What's the best way to do it?
What do you mean "best way"? I think this is the most straightforward way ... hopefully that is what you meant :)
fopen the input and output files with binary mode
FILE *exein, *exeout;
exein = fopen("filein.exe", "rb");
if (exein == NULL) {
/* handle error */
perror("file open for reading");
exit(EXIT_FAILURE);
}
exeout = fopen("fileout.exe", "wb");
if (exeout == NULL) {
/* handle error */
perror("file open for writing");
exit(EXIT_FAILURE);
}
fread and fwrite
size_t n, m;
unsigned char buff[8192];
do {
n = fread(buff, 1, sizeof buff, exein);
if (n) m = fwrite(buff, 1, n, exeout);
else m = 0;
} while ((n > 0) && (n == m));
if (m) perror("copy");
and finally close the files
if (fclose(exeout)) perror("close output file");
if (fclose(exein)) perror("close input file");
Have fun!
Windows has a CopyFile API (if you don't mind being platform specific). One thing to be careful of these days is making sure you have permissions to write to the destination area.
Make sure you open the files with the O_BINARY option if you use open() and file descriptors, or with the letter "b" in the mode string if you use fopen(). Note that O_BINARY is not standard except on Windows; however, you can treat it (or define it) as 0 on Unix and all will be fine. If you are using a pure Windows API, then make sure you are doing the equivalent - make sure you specify that the file is treated as a binary file.
You can use this to copy Binary Files:
int get_file_size(char *source)
{
FILE *fichier = fopen(source,"rb");
fseek(fichier,0,SEEK_END);
int size = ftell(fichier);
fseek(fichier,0,SEEK_SET);
fclose(fichier);
return size;
}
void copy(char *source, char *dest)
{
int srcsize = get_file_size(source);
char *data = (char *)malloc(srcsize);
int fsource = open(source,O_RDONLY | O_BINARY);
int fdest = open(dest,O_WRONLY | O_CREAT | O_BINARY);
read(fsource,data,srcsize);
write(fdest,data,srcsize);
close(fsource);
close(fdest);
}
You can use function of 'dos.h' for low-level IO operation.
Following code illustrate use of them. Hope it will helpful
#include<stdio.h>
#include<dos.h>
#include<FCNTL.H>
#include<SYS\STAT.H>
void main()
{
char s_file[100],d_file[100],buf[512];
short char copy='y';
int in_handle,out_handle,flg,len;
printf("\nEnter File Name : ");
fflush(stdin);
gets(s_file);
printf("\nEnter Destination File Name : ");
fflush(stdin);
gets(d_file);
// open file for reading
in_handle=open(s_file,O_RDONLY | O_BINARY);
if(in_handle<0)
{
printf("\nSource File not Found... ");
}
else
{
// open file for writing
out_handle=open(d_file,O_CREAT|O_WRONLY|O_BINARY,S_IWRITE);
while((len=read(in_handle,buf,512))>0)
{
flg=write(out_handle,buf,len);
if(flg==-1)
break;
}
if(flg==-1)
{
printf("Unable to Create");
}
else
{
printf("File Created");
}
}
if(!(in_handle<0))
close(in_handle);
if(!(out_handle<0));
close(out_handle);
}
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("source file","rb");
if(fp1==NULL)
exit(1);
fp2=fopen("destination file","wb");
if(fp2==NULL)
exit(1);
while((c=fgetc(fp1))!=EOF)
fputc(c,fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
http://www.cs.bu.edu/teaching/c/file-io/intro/
#include <ctype.h>
#include <stdio.h>
#define BUFSIZE 1024
int main(int argc, char **argv)
{
charmybuf[BUFSIZE] = { 0 }, *p = NULL;
FILE *ifd = NULL, *ofd = NULL;
ifp = fopen( argv[1], “r” );
ofp = fopen( argv[2], “w” );
assert(ifp!=NULL);
assert(ofp!=NULL);
while ( ( n = fread( mybuf, sizeof(char), BUFSIZE ,ifd) ) > 0 )
{
fwrite(mybuf, sizeof(char),BUFSIZE,ofd);
}
fclose(ifd);
fclose(ofd);
return 0;
}

How can I extract pictures from a WBC file in C?

Someone ask me to help them extract their pictures from a Web Shots image collection file (.WBC). I tried XnView but it did not work. How can I do this in C?
From Mike:
I hacked together some code to do the job. Here it is. It's not production quality code, so if you do not understand it then do not run it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void save_image(const char* filename, FILE* in_fp)
{
char buf[4096];
size_t read;
FILE *fp;
fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "cannot open file.");
exit(1);
}
do {
read = fread(buf,1,sizeof(buf),in_fp);
fwrite(buf, 1, read, fp);
} while (read);
fclose(fp);
}
int main(int argc, char* argv[])
{
char buf[4096];
unsigned int read, read_tot = 0;
FILE *fp;
int image_count = 1;
char filename[255];
unsigned int i;
char pattern[] = "JFIF";
int pi = 0;
long int curpos;
char pad[50];
char src_filename[] =
"C:\\Documents and Settings\\mikeking\\Desktop\\WBC\\"
"Custom - CATHYS WEDDING.wbc";
char des_directory[] = "C:\\Documents and Settings\\mikeking\\Desktop\\F\\";
fp = fopen(src_filename, "rb");
if (!fp) {
fprintf(stderr, "cannot open file.");
exit(1);
}
do {
read = fread(buf,1,sizeof(buf),fp);
for(i=0; i<read; i++){
if (buf[i] == pattern[pi]) {
pi++;
if (pi == sizeof(pattern)) {
strcpy(filename, des_directory);
itoa(image_count, pad, 10);
image_count++;
strcat(filename, pad);
strcat(filename, ".jpg");
curpos = ftell(fp);
fseek(fp,read_tot+i-10,SEEK_SET);
save_image(filename,fp);
fseek(fp,curpos,SEEK_SET);
}
} else {
pi = 0;
}
}
read_tot += read;
} while (read);
fclose(fp);
return 0;
}

Resources