mardi 3 novembre 2020

Generate function using /dev/random showing Segmentation fault (core dumped) error when called

The following code is supposed to be run from terminal so you should be able to choose different functions by just typing the name of a function and providing it with arguments (for example ./program generate dog 5 20 should generate 5 lines each with 20 characters and save them into the the file called dog). The other functions that you can see here may be a part of a problem that's why I'm including them although the problem itself occurs when I try to generate things. As you can see other functions are just declarations now mostly cuz I wanted to test if the first one was working correctly before going to others.

I was thinking that maybe I should write something that would actually take data from console input and put them directly into what's called "a" and "b" but if there is a problem with the function itself it won't help at all.

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>



void generate(const char *str, int a, int b);

int main(int argc, char *argv[]){

    int if_generate = (strcmp("generate", argv[1])==0);
    
    
    if (if_generate){
    generate(argv[2], argv[3], argv[4]);
}else{
printf("wrong function name");
}


}

void generate(const char *str, int a, int b){

    int n,m;
    int myFile = open(str, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR |S_IWUSR);
    int randomiser = open("/dev/urandom", O_RDONLY);
    char bufor[b+1];
    for(n=0; n<a; n++){
    for (m=0; m<b; m++){
        read (randomiser, &bufor, 1);
        write (myFile, &bufor, 1);
    }
        write(myFile, "\n", 1);
    }
    
}
    

    



Aucun commentaire:

Enregistrer un commentaire