繁体   English   中英

从.txt文件读取随机行

[英]Read random line from .txt file

我正在尝试通过读取.txt文件中的随机单词来升级我的Hangman游戏。 问题是,我不知道如何从.txt文件中读取随机行。 .txt文件的每一行都包含一个单词。

void ler_palavras()
{
    FILE *words;

    if ((words = fopen("words.txt", "r")) == NULL) {
        printf("Error! opening file");
        exit(1);
    }

    // reads text until newline
    fscanf(words,"%[^\n]", word);
    fclose(words);
}

如果由于某种原因不能将整个行集加载到内存中(太大或其他大小),则可以使用一种方法从流条目集中选择一个随机条目。 它不会无限扩展,并且会显示出很小的偏差,但这是一个游戏,而不是加密技术,因此不应该成为破坏交易的工具。

逻辑是:

  1. 声明一个缓冲区来容纳单词
  2. 开启档案
  3. 对于每一行:
    • 增加一个计数器,指示您所在的行
    • 生成一个随机double drand48 (例如,使用drand48或任何可用的PRNG设施)
    • 如果1.0 / lineno > randval ,请用当前行中的单词替换当前存储的单词(因此第一行是自动存储的,第二行有50%的可能性替换它,第三行有33%的可能性替换,依此类推)
  4. 当您用完所有行时,存储在word就是您的选择

假设行数足够小(并且PRNG产生的double的范围足够细),这将使选择给定行的可能性尽可能接近; 两行,每行有50/50的投篮,三行是33.33 ...%,依此类推。

我现在缺少C编译器,但是基本代码如下:

/* Returns a random line (w/o newline) from the file provided */
char* choose_random_word(const char *filename) {
    FILE *f;
    size_t lineno = 0;
    size_t selectlen;
    char selected[256]; /* Arbitrary, make it whatever size makes sense */
    char current[256];
    selected[0] = '\0'; /* Don't crash if file is empty */

    f = fopen(filename, "r"); /* Add your own error checking */
    while (fgets(current, sizeof(current), f)) {
        if (drand48() < 1.0 / ++lineno) {
            strcpy(selected, current);
        }
    }
    fclose(f);
    selectlen = strlen(selected);
    if (selectlen > 0 && selected[selectlen-1] == '\n') {
        selected[selectlen-1] = '\0';
    }
    return strdup(selected);
}

rand()有其局限性,包括仅生成0RAND_MAX值,并且文件可以有很多次RAND_MAX行。 假设行数为RAND_MAX/10或更小,则将满足OP的目标。

执行一次通过以计算行数。 -> lc

对于每个所需的无规线,重新读取该文件的行,从之前的一些随机数开始向上行索引[0... lc-1]范围内。

然后只需阅读并打印该行。 不需要行缓冲区。 该文件是行缓冲区。 该代码将Line_Count()重新用于Line_Count()数计算和读取直到第n行。

#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

// Return line count, but stop once the count exceeds a maximum
int Line_Count(FILE *istream, int line_index) {
  int lc = 0;
  int previous = '\n';
  int ch;
  rewind(istream);
  while (line_index > 0 && (ch = fgetc(istream)) != EOF) {
    if (ch == '\n') {
      line_index--;
    }
    if (previous == '\n') {
      lc++;
    }
    previous = ch;
  }
  return lc;
}

void print_random_line(FILE *istream, int line_index) {
  printf("%8d: <", line_index + 1);
  Line_Count(istream, line_index);
  int ch;
  while ((ch = fgetc(istream)) != EOF && ch != '\n') {
    if (isprint(ch)) {
      putchar(ch);
    }
  }
  printf(">\n");
}

int main() {
  srand((unsigned) time(NULL));
  FILE *istream = fopen("test.txt", "r");
  assert(istream);
  int lc = Line_Count(istream, RAND_MAX);
  assert(lc && lc < RAND_MAX);
  for (int i = 0; i < 5; i++) {
    print_random_line(istream, rand() % lc);
  }
  fclose(istream);
}

这是另一个仍然受RAND_MAX限制的解决方案,它不需要读取每一行直到所选的行。 这个想法是使用一个二进制文件将每个单词存储在相同数量的字节中,因此可以使用fseek()fread()来访问任何单词。 文件中的第一个条目是一个long值,用于存储文件中的单词数。 添加单词时,此值将更新。

这是一个寻找普通文本文件wordlist.txt ,该文件在每一行上都有一个单词。 如果找到,程序将更新(或创建,如有必要)名为wordlist.fmt的文件。 更新功能从文本文件中读取每个单词,跳过空白行,并将其存储在固定数目的字节中的二进制文件中。 读完所有单词后,单词计数将更新。 使用文本文件运行该程序一次后,应删除该文本文件,否则下一次运行将再次添加这些单词。 .fmt文件应保留,如果要添加更多单词,只需将新的文本文件放入可执行文件的目录中,然后再次运行即可。

打印五个随机单词的循环将生成一个随机数,使用该数字将其移动到包含单词的文件位置,然后将该单词读入数组并进行打印。

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

#define RAW_WORDS  "wordlist.txt"
#define FMT_WORDS  "wordlist.fmt"
#define OFFSET_SZ  (sizeof(long))
#define MAXWORD    30

void update_words(FILE *fp_fmt, FILE *fp_raw);
void strip(char *str);

int main(void)
{
    FILE *raw_words, *formatted_words;
    char word[MAXWORD];
    long wordcount;
    int i;
    int wpos;

    raw_words = fopen(RAW_WORDS, "r");

    /* Try to open existing file for update, otherwise open new file */ 
    if ((formatted_words = fopen(FMT_WORDS, "r+b")) == NULL){
        if ((formatted_words = fopen(FMT_WORDS, "w+b")) == NULL) {
            fprintf(stderr, "Unable to open file %s\n", FMT_WORDS);
            exit(EXIT_FAILURE);
        } else {                    // initialize file wordcount
            wordcount = 0L;
            fwrite(&wordcount, OFFSET_SZ, 1, formatted_words);
            fflush(formatted_words);
        }
    }

    /* Update FMT_WORDS file if RAW_WORDS is present */
    if (raw_words != NULL)
        update_words(formatted_words, raw_words);

    /* Get 5 random words and print them */
    srand((unsigned)time(NULL));

    rewind(formatted_words);
    fread(&wordcount, OFFSET_SZ, 1, formatted_words);

    printf("Five random words from %s:\n", FMT_WORDS);
    for (i = 0; i < 5; i++) {
        wpos = rand() % wordcount;
        fseek(formatted_words, wpos * MAXWORD + OFFSET_SZ, SEEK_SET);
        fread(word, MAXWORD, 1, formatted_words);
        puts(word);
    }

    if (raw_words && (fclose(raw_words) != 0))
        fprintf(stderr, "Unable to close file %s\n", RAW_WORDS);
    if (fclose(formatted_words) != 0)
        fprintf(stderr, "Unable to close file %s\n", FMT_WORDS);

    return 0;
}

void update_words(FILE *fp_fmt, FILE *fp_raw)
{
    char word[MAXWORD];
    long wordcount;

    /* Read in wordcount and move to end of file */
    rewind(fp_fmt);
    fread(&wordcount, OFFSET_SZ, 1, fp_fmt);
    fseek(fp_fmt, wordcount * MAXWORD, SEEK_CUR);

    /* Write formatted words, skipping blank lines */
    while (fgets(word, MAXWORD, fp_raw) != NULL) {
        if (word[0] != '\n') {
            strip(word);
            if (fwrite(word, MAXWORD, 1, fp_fmt) != 1) {
                fprintf(stderr, "Error writing to %s\n", FMT_WORDS);
                exit(EXIT_FAILURE);
            }
            ++wordcount;
        }
    }

    /* Update wordcount in file and flush output */
    rewind(fp_fmt);
    fwrite(&wordcount, OFFSET_SZ, 1, fp_fmt);
    fflush(fp_fmt);
}

void strip(char *str)
{
    while (*str != '\n' && *str != '\0')
        str++;
    *str = '\0';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM