试题描述:(1) 产生500个100以内的随机数,以如下的格式写入文件(每写一个数字后换行):
10
20
30
...
(2) 读取上述文件中的内容,将文件中的每行数字分别放入一个数组a[1024]中,然后打印该数组
C语言实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void write_file()
{
FILE *fp = fopen("test.txt", "w");
if(fp == NULL)
{
perror("fopen:");
}
char buf[100];
srand((unsigned int) time(NULL));
int i = 0;
int num = 0;
for(i=0;i<500;i++)
{
num = rand() % 100;
sprintf(buf, "%d\n", num);
fputs(buf, fp);
}
fclose(fp);
fp = NULL;
}
void read_file()
{
FILE *fp = fopen("test.txt", "r");
if(fp == NULL)
{
perror("fopen: ");
}
int i = 0;
int num = 0;
int a[1024];
char buf[100];
while(1)
{
fgets(buf, sizeof(buf), fp);
if(feof(fp))
{
break;
}
sscanf(buf, "%d\n", &num);
a[i] = num;
i++;
}
int n = i;
for(i=0;i<n;i++)
{
printf("%d ", a[i]);
}
printf("\n");
fclose(fp);
fp = NULL;
}
int main()
{
write_file();
read_file();
return 0;
}