jeudi 16 avril 2020

How to Read and Return Random Line From Txt(C)

Text include 100 word in every line,1 word max 20 character below code prints same thing,ı want this random,how to edit my code? Two printf functions print the same word. I browsed related all topics but I wasn't enlightened, because I'm a new learner.

int main(){
char *str;
    printf("%s",word("words.txt",str));
    printf("%s",word("words.txt",str));
}


char *word(char *file, char *str0) {
    int end, loop, line;
    int i;


   str0 = (char *)malloc(20);

    FILE *fd = fopen(file, "r");

    if (fd == NULL) {
        printf("Failed to open file\n");
        return (NULL);
    }

    srand(time(NULL));
    line = rand() % 100 + 1;

    for (end = loop = 0; loop < line; ++loop) {
        if (NULL == fgets(str0, 20, fd)) {
            end = 1;
            break;
        }
    }

    if (!end){
            fclose(fd);

            return str0;
            free(str0);

    }
}



Aucun commentaire:

Enregistrer un commentaire