问题出处:《C专家编程》A.9(记不太清了)
编译环境vs08。
/*****************************************
*从打开的字符串文件中随机提取字符串
******************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define FILEPATH "hello.txt"
#define MAXLEN 255
void randStr(FILE *fp, char *str);
int main(int argc, char **argv)
{
FILE *fp;
char *str = (char *)malloc(MAXLEN+1);
if (str == NULL)
{
return 1;
}
if ( (fp = fopen(FILEPATH, "r")) == NULL)
{
printf("Open file error!\n");
}
else
{
randStr(fp, str);
printf("%s", str);
fclose(fp);
free(str);
}
return 0;
}
void randStr(FILE *fp, char *str)
{
int lineNum = 0;
srand(time(NULL));
char buf[MAXLEN];
if (NULL == fp)
{
return ;
}
while ( (fgets(buf, MAXLEN, fp)) != NULL)
{
lineNum++;
if (rand()%lineNum < 1)
{
strcpy(str, buf);
}
}
}