segment fault error in encrypt files smaller than 1Kbyte - c

i write this program for encrypt any file with any size but if file will smaller than 1Kbyte my program give me segment fault error whats wrong?
#include <stdio.h>
#include <stdlib.h>
long int findsize(char file_name[])
{
FILE* fp = fopen(file_name, "r");
if (fp == NULL) {
printf("File Not Found!\n");
return -1;
}
fseek(fp, 0L, SEEK_END);
long int res = ftell(fp);
fclose(fp);
return res;
}
int main ()
{
FILE *fptr;
char path[256];
char* data;
int passcode;
printf("Enter the path of file : ");
scanf("%s",path);
long int file_size = findsize(path);
data = malloc(file_size);
fptr = fopen(path,"rb");
int i = 0;
while (!feof(fptr))
data[i++] = fgetc(fptr);
fclose(fptr);
fptr = fopen(path, "wb");
for (int j=0; j<i-1; j++)
fputc((data[j] ^ 0x60), fptr);
fclose(fptr);
free(data);
return 0;
}
my program can encrypt files bigger than 1GByte but. what should i do?

Related

Reading a file in C on Linux

How do I read a file into a string on Linux in C?
I came up with some code, but it's not working, and idk why. fgetc() always returns -1.
The file structure is something like this
.:
Files/
main.c
makefile
./Files:
test
Contents of main.c:
#include <stdio.h>
int fileLength(const char filePath[]);
void readFile(const char filePath[], char* outString);
int main()
{
char fileContents[fileLength("Files/test")];
readFile("Files/test", &fileContents);
printf("DEBUG: Address of fileContents is 0x%x\n", &fileContents);
printf("File contents:\n%s\n", fileContents);
return 0;
}
int fileLength(const char filePath[])
{
//Open the file
FILE* file;
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
return -1;
}
//Find the length
fseek(file, 0, SEEK_END);
return ftell(file);
}
void readFile(const char filePath[], char* outString)
{
FILE* file;
//File reading
printf("DEBUG: File path is %s\n", filePath);
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
exit(1);
}
//Get length of file and allocate the according amount of memory
fseek(file, 0, SEEK_END);
int fileLength = ftell(file);
printf("DEBUG: File length is %i\n", fileLength);
//Allocate string
char fileContent[fileLength];
//Read file to string
printf("DEBUG: File contents as digits:\n");
for (int i = 0; i < fileLength; i++)
{
fileContent[i] = fgetc(file);
printf("%d ", fileContent[i]);
}
printf("\n");
printf("DEBUG: Contents of file are:\n%s\n", fileContent);
fclose(file);
printf("DEBUG: outString is pointing to 0x%x\n", outString);
*outString = fileContent;
}
The output is usually just a bunch of question mark diamond things (running in terminal) that match the length of the file with a few other random chars thrown in at the end. The chars at the end change every time the program is run.
kaylum was right, the solution was to:
rewind() after finding the file length in readFile()
remember to fclose() when done
write directly to outString instead of using fileContent
The final code of main.c comes out to be:
#include <stdio.h>
int fileLength(const char filePath[]);
void readFile(const char filePath[], char* outString);
int main()
{
char fileContents[fileLength("Files/test")];
readFile("Files/test", &fileContents);
printf("File contents:\n%s\n", fileContents);
return 0;
}
int fileLength(const char filePath[])
{
//Open the file
FILE* file;
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
return -1;
}
//Find the length
fseek(file, 0, SEEK_END);
int length = ftell(file);
fclose(file);
return length;
}
void readFile(const char filePath[], char* outString)
{
FILE* file;
//File reading
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
exit(1);
}
//Get length of file and allocate the according amount of memory
fseek(file, 0, SEEK_END);
int fileLength = ftell(file);
rewind(file);
//Read file to string
for (int i = 0; i < fileLength; i++)
outString[i] = fgetc(file);
fclose(file);
}

fread does not read the entire file

I used fread to read the entire file but I am getting only the first of it, why is that?
My code:
#define MAXBUFLEN 4096
int main(){
int ret =0;
char source[MAXBUFLEN + 1];
FILE *fp = fopen("test", "r");
if (fp != NULL)
{
rewind(fp);
ret = fread(source, 1, MAXBUFLEN, fp);
printf("ret : %d %s",ret,source);
fclose(fp);
}
return 0;
}
The file text:
/# cat test
/usr/sbin/sshd-p 1234-o LoginGraceTime=30-o ClientAliveInterval=600-o ClientAliveCountMax=0-o TCPKeepAlive=no-o MaxSessions=1-o MaxStartups=1-o MaxAuthTries=3
My program output :
ret : 167 /usr/sbin/sshd
What is the easiest way of reading this entire file? (which is not standard and not end with \n)?
Answer : there was 0 between each word in this file, it was not standard word but ^# which is recored seperate in Linux . The code was fixed by this:
#include <stdio.h>
void removeNewLine(char * str,int len);
#define MAXBUFLEN 4096
int main(){
char source[MAXBUFLEN + 1];
FILE *fp = fopen("test", "r");
int ret =0;
if (fp != NULL)
{
rewind(fp);
ret = fread(source, 1,MAXBUFLEN, fp);
removeNewLine(source,ret);
fclose(fp);
}
return 0;
}
void removeNewLine(char * str,int len){
int i=0;
for(i=0; i<len;i++) {
if((int)str[i]==0 )
{
str[i]=' ';
}
}
str[len] = 0;
printf("%s",str);
}

Read wrong values from binary file

I want to take an array of structs so I can sort it by name and write it on a txt file. But it takes wrong values like strange symbols or numbers. Anyone knows what is wrong?
typedef struct candidato Candidato;
struct candidato {
char inscr[10];
char nome[44];
int periodo;
int posicao;
char curso[30];
};
FILE *fp = fopen(filename, "rb");
if (fp == NULL)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return ;
}
fseek(fp, 0, SEEK_END);
size_t sz = ftell(fp);
int ncand = sz/sizeof(Candidato);
rewind(fp);
Candidato *arr = malloc(sz);
if (arr == 0)
{
fprintf(stderr, "Failed to allocate %zu bytes memory\n", sz);
return ;
}
printf("%d \n",ncand);
int i;
int cont;
for (i = 0; fread(&arr[i], sizeof(Candidato), 1, fp) == 1; i++){
printf("%s\n",arr[i].nome); //test if it got what I want
}
fclose(fp);
I solved my problem and here's the working code:
FILE *f = fopen (filename, "rb");
if(f==NULL){
printf("Erro na abertura do arquivo. \n");
system("pause");
return;
}
fseek(f, 0, SEEK_END);
int sz = ftell(f);
rewind(f);
Candidato arr[sz/sizeof(Candidato)];
int i;
for (i = 0; fread(&arr[i], sizeof(Candidato), 1, f) == 1; i++) {
printf("%s %i \n",arr[i].nome,arr[i].inscr);
}

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;
}

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