在windows7下,从D:\\nolt\\nlot.txt获取教师名单(name list of teachers),从d:\\nolt\\nlos.txt获取学生名单(name list of students),用户依次输入每位教师分配的学生数,程序接收输入后将分配结果存到d:\\nolt\\fod.txt文件中。程序清单如下:
#include<stdio.h>
#include<time.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
FILE *fpnlot ; //name list of teachers
FILE *fpnlos ; //name list of students
FILE *fpfod ; //the result
int noas , totalnoas =0; //number of assigned students,total number of students
int * seqos ; //sequence of students
static int arr[100];
int Rand( int X , int Y )//产生随机数
{
int temp;
if(X>Y)
{
temp=X;
X=Y;
Y=temp;
}
return rand()%(Y-X+1)+X;
}
int * getrand(void) //generate the random array index from 0to99
{
int i;
int r;
int temp;
srand((unsigned)time(NULL));
for(i=0;i<100;i++) arr[i]=i+1;
for(i=0;i<100;i++)
{
r=Rand(0,99);
temp=arr[i];
arr[i]=arr[r];
arr[r]=temp;
}
for(i=0;i<100;i++) //added
{printf("arr=%d ",arr[i]);} //added
return arr;
}
int writelot(void) //write list of teachers to fod
{
char nameot = 0;
while(1)
{
nameot = getc(fpnlot);
if (nameot == '\n' )
break;
else
putc(nameot,fpfod);
}
fprintf(fpfod,"\n");
return 0;
}
int writelos(void) //write list of students to fod
{
int count , j , k = 0;
char nos;
k = totalnoas;//随机数学生序号偏移量
for(count=0;count<noas;count++)//打印学生名字次数
{
rewind(fpnlos);//回到学生名单开头
printf("count:%d ",count);
j= arr[0+k] ;//获得与学生序号对应的随机数
printf("j:%d k:%d \n",j,k);
k++;//随机数组序数加一
while(1)
{
for(; j>0 ; j--)
{
while((nos=fgetc(fpnlos))!= '\n');
}
if ((nos=fgetc(fpnlos)) == '\n')
{break;
}
else
{fputc(nos,fpfod);}
}
fprintf(fpfod,"\n");
}
fprintf(fpfod,"\n");
return 0;
}
int main()
{
int i,not ,judgescanf = 0 ;
fpnlot=fopen("D:\\nolt\\nlot.txt","r");
if (fpnlot== NULL )
{
perror("nlot.txt can't be open");
exit(EXIT_FAILURE);
}
fpnlos=fopen("d:\\nolt\\nlos.txt","r");
if (fpnlos== NULL)
{
printf("nlos.txt can't be open");
exit(EXIT_FAILURE);
}
fpfod=fopen("d:\\nolt\\fod.txt","a+");
if (fpfod == NULL)
{
printf("fod.txt can't be open");
exit(EXIT_FAILURE);
}
seqos = getrand();
not=8;
for (i=0;i<not;i++)
{
writelot();
do { //from the writelot()
/*if (noas>99-totalnoas)
break;*/
printf("%d please enter the number to assign:",totalnoas);
judgescanf=scanf("%d",&noas);
getchar();
}
while ((noas>99-totalnoas)||(judgescanf!=1)||noas<0);
writelos();
fprintf(fpfod,"\0");
totalnoas += noas;
}
if ( fclose(fpnlot)!=0)
printf("error close");
if ( fclose(fpnlos)!=0)
printf("error close");
if ( fclose(fpfod)!=0)
printf("error close");
return 0;
}