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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…