Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

Chose random a word from txt file and mark it as chosen in C

I want to randomly extract a word from the text file and mark it as chosen.(I want to add a * at the end of the word) I can extract the words random but when I want to mark the word as chosen (add '*') the * character is added at the end of the file and not at the end of the chosen word. I don't know why. Does anyone have an idea?

#include <stdlib.h>
#include<stdio.h>
#include <time.h>
#include <unistd.h>

int main(void)
{
char secret[50];
    unsigned long fileLen;
    srand(time(NULL));

        FILE *fp = fopen("input.txt", "a+");
        if( fp == NULL ){
            fprintf(stderr, "No such file or directory: %s
");
            return 1;
        }

    //Get file length
        fseek(fp, 0, SEEK_END);
        fileLen=ftell(fp);
        fseek(fp, 0, SEEK_SET);
        printf("fileLen --------->%ld
", fileLen);

    do{

        // generate random number between 0 and filesize
        unsigned long random = (rand() % fileLen) + 1;

        // seek to the random position of file
        fseek(fp, random, SEEK_SET);
        // get next word in row ;)

        printf("Random ------->%ld
", random);//testing purpose
        printf("ftell --------->%ld
", ftell(fp));

        int result = fscanf(fp, "%*s %s", secret);
        printf("Chosen word is: %s 
", secret);

        int len = strlen(secret);
        if(result)
            {
                fseek(fp, len, SEEK_CUR);
                fputc('*', fp); // put a '*' at the end of the word that was chosen
            }

        if( result != 0 )
            break;
    } while(1);

fclose(fp);

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using fseek to get the length is good, and logically, it stops at the end of the file, the issue is that is stays there (that's why * is in the end), so after using it, you are at the end of the file, use rewind(fp) to return to the beginning of the file after using fseek(fp) to get its length.

Also, read Eugene Sh's comment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...