随机数生成并写入文件(C实现)

#include   
#include   
#include   
  
//生成随机数列  
int write()  
{  
    int i,j;  
    FILE *pf = NULL;  
    int a1[50],a2[50];  
    srand((unsigned)time(NULL));//随机种子  
    pf = fopen("C:\\Users\\Administrator\\Desktop\\data.txt","a");  
    //生成数列  
    for(i=0; i<50; i++)  
    {  
        a1[i] = 1+(int)(5399.0*rand()/(RAND_MAX+1.0));
        a2[i] = 1+(int)(5.0*rand()/(RAND_MAX+1.0));
    }  
    //格式化输出到文件中  
    for(i=0; i<47; i++)  
    {  
    		
            fprintf(pf,"%-5d",a1[i+j]);  
            fprintf(pf,"%-5d",a2[i+j]);
        	fprintf(pf,"\n");  
    }  
    fclose(pf);  
    return 0;  
}  
int read()  
{  
    int i,j;  
    FILE *pf;  
    int arr[2000];  
    if((pf = fopen("sort.txt","r"))==NULL)  
    {  
        printf("Error\n");  
        system("PAUSE");  
        exit(1);  
    }  
    //读取文件内容到数列  
    for(i=0; i<200; i++)  
    {  
        for(j=0; j<10; j++)  
        {  
            fscanf(pf,"%d",&arr[i*10+j]);  
        }  
        fscanf(pf,"\n");  
    }  
    fclose(pf);  
    //将数列输出到屏幕  
    for(i=0; i<200; i++)  
    {  
        for(j=0; j<10; j++)  
        {  
            printf("%-5d",arr[i*10+j]);  
        }  
        printf("\n");  
    }  
  
    return 0;  
}  

int main(){
	
	write();
	
	return 0;
}

你可能感兴趣的:(学习笔记)