c语言往内存中写入随机数,C语言往文件内写入随机数并进行排序

创建文本文件并在该文件内写入100个0-100的随机数,然后对该文件内的随机数进行从小到大的排序,源码如下:

#include #include #include #include #define MAX 100

int file_write(void)

{

FILE *fp = NULL;

fp = fopen("RandomSort.txt", "w");

if(fp == NULL)

{

perror("File_write fopen error");

return -1;

}

srand((unsigned int)time(NULL));

int num = 0;

for(int i = 0; i < MAX; i++)

{

num = rand() % 100;

fprintf(fp, "%d\n", num);

}

fclose(fp);

fp = NULL;

return 0;

}

int file_read(void)

{

FILE *fp = NULL;

fp = fopen("RandomSort.txt", "r");

if(fp == NULL)

{

perror("File_read fopen error");

return -1;

}

int buf[1024];

int times = 0;

while(1)

{

fscanf(fp, "%d\n", &buf[times]);

times++;

if(feof(fp))

{

break;

}

}

int total = times;

int temp;

for(int i = 0; i < total - 1; i++)

{

for(int j = 0; j < total - 1 - i; j++)

{

if(buf[j] > buf[j + 1])

{

temp = buf[j];

buf[j] = buf[j + 1];

buf[j + 1] = temp;

}

}

}

fclose(fp);

fp = fopen("RandomSort.txt", "w");

for(int i = 0; i < MAX; i++)

{

fprintf(fp, "%d\n", buf[i]);

}

fclose(fp);

fp = NULL;

return 0;

}

int main(void)

{

file_write();

file_read();

return 0;

}

分析:

① file_write()函数

int file_write(void)

{

FILE *fp = NULL;

fp = fopen("RandomSort.txt", "w");

if(fp == NULL)

{

perror("File_write fopen error");

return -1;

}

srand((unsigned int)time(NULL));

int num = 0;

for(int i = 0; i < MAX; i++)

{

num = rand() % 100;

fprintf(fp, "%d\n", num);

}

fclose(fp);

fp = NULL;

return 0;

}

该函数先创建了一个文本文件RandomSort.txt并以只写的方式打开,设置好随机数种子srand(),rand()%100是将随机数限制在100以内,并写入RandomSort.txt,结果如下图(这里只显示一部分数据):

5985f8f52811ebb1750fc333b507fc6f.png

② file_read()函数

int file_read(void)

{

FILE *fp = NULL;

fp = fopen("RandomSort.txt", "r");

if(fp == NULL)

{

perror("File_read fopen error");

return -1;

}

int buf[1024];

int times = 0;

while(1)

{

fscanf(fp, "%d\n", &buf[times]);

times++;

if(feof(fp))

{

break;

}

}

int total = times;

int temp;

for(int i = 0; i < total - 1; i++)

{

for(int j = 0; j < total - 1 - i; j++)

{

if(buf[j] > buf[j + 1])

{

temp = buf[j];

buf[j] = buf[j + 1];

buf[j + 1] = temp;

}

}

}

fclose(fp);

fp = fopen("RandomSort.txt", "w");

for(int i = 0; i < MAX; i++)

{

fprintf(fp, "%d\n", buf[i]);

}

fclose(fp);

fp = NULL;

return 0;

}

该函数以只写的方式打开文本文件RandomSort.txt,使用fscanf()将文件内的"%d\n"形式的数据一个一个取出并存放到buf数组里面,知道结尾处if(feof(fp))为真跳出循环,接着对存放到buf的这些随机数进行从小到大的排序,然后关闭文件并重新以只写的方式打开文本文件RandomSort.txt并将这些数据重新写入,结果如下图(这里只显示一部分数据)。

6f92693e23151af8826775d00f4b5149.png

如果有什么不懂的地方或者想要一起学习交流的朋友可以加我微信:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值