从文件中随机提取一个字符串

来源:互联网 发布:java 虚拟文件系统 编辑:程序博客网 时间:2024/05/24 04:56

 

#include <stdio.h>  #include <string.h>  #include <stdlib.h>  #include <time.h>    #define random(x) (rand() % x) //产生x内的随机函数  #define RAND_N 1000    //自定义随机器  void my_random(char *buf1, char *buf2, int count)  {      //判断范围      if(random(RAND_N) < RAND_N / count)      {          strcpy(buf1, buf2);      }  }    //主函数  int main()  {      FILE *fp;      int count = 0;      char buf1[100], buf2[100];            if ((fp = fopen("d:/test.txt", "r")) == NULL) {          fprintf(stderr, "open error");          exit(0);      }            if(fscanf(fp, "%s", buf1) == EOF)      {          printf("file is null\n");          return 0;      }        count++;            srand((int)time(0));//设置随机数种子,srand不能调用两次以上      for(count++; fscanf(fp, "%s", buf2) != EOF; count++)      {           my_random(buf1, buf2, count);        }            fclose(fp);      printf("随即读取的字符串为 : %s\n", buf1);            return 0;  }