0

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?

  • 1
    https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Mat Apr 24 '20 at 08:31
  • 1
    Don't use `feof` for this. Just check the value returned by `fgetc`, and check for `EOF`. And it should be a simple matter to check that `i` is less than `file_size` *before* storing to `data`. Make sure you're in sync, rather than corrupting memory and getting a seg fault. Code defensively. – Tom Karzes Apr 24 '20 at 08:35
  • Did you use your debugger? And BTW: `fopen` can fail, you absolutely need to check that in your code. What do you think happens if the user entered a file name that does not exist? And you need `"rb"` instead of `"rb"` in `findsize`. – Jabberwocky Apr 24 '20 at 08:50
  • when i run debugger it says no such file or dirctory – Humed keigho May 24 '20 at 15:05

0 Answers0