#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define MAX 500
void write_file()
{
int index = 0, num = 0;
FILE *fp;
char buf[1024];
fp = fopen("1.txt","w");
if(NULL == fp
{
perror("write_file fopen");
return;
}
srand((unsigned int) time(NULL));
for(index = 0; index < MAX; index++)
{
num = rand()%100;
sprintf(buf,"%d\n",num);
fputs(buf,fp);
}
fclose(fp);
}
void read_file()
{
int index = 0, num = 0, a[1024],n = 0;
FILE *fp;
char buf[1024];
fp = fopen("1.txt","r");
if(NULL == fp
{
perror("read_file fopen");
return;
}
while(1)
{
fgets(buf,sizeof(buf)-1,fp);
if(feof(fp))//如果到文件结尾,则跳出循环
{
break;
}
sscanf(buf,"%d\n",&num);
a[index++] = num;
}
n = index;
printf("number is %d\n",n);
for(index = 0; index < n; index++)
{
printf("%d\n",a[index]);
}
fclose(fp);
}
int main()
{
write_file();
read_file();
return 0;
}