案例一:文件1生成五十道随机四则运算题,解题并将答案写入文件2。
案例二:文件1写入一百个随机数,将其排序并写入文件2。
案例一:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//出题
void setQ()
{
//设置随机数种子
srand((size_t)time(NULL));
//创建变量
int num1 = 0;
int num2 = 0;
char ch = 0;
char oper[] = { '+','-','*','/' };
FILE* f_write = fopen("text.txt", "w");
if (f_write == NULL)
{
printf("文件打开失败\n");
return;
}
int i = 0;
for (i = 0; i < 50; i++)
{
//产生随机数
num1 = rand() % 100 + 1; // 产生1~100的随机数
num2 = rand() % 100 + 1;
ch = oper[rand() % 4]; //产生0~3的随机数
//写文件
char msg[64] = { 0 };
sprintf(msg, "%d %c %d =\n", num1, ch, num2);//拼接字符串
//写到文件中
//printf("%s", msg);
fputs(msg, f_write);
}
//关闭文件
fclose(f_write);
printf("50道题目生成完毕!\n");
}
//解题
void ansQ()
{
FILE* f1 = fopen("text.txt", "r");
FILE* f2 = fopen("answer.txt", "w");
if (f1 ==NULL || f2 == NULL)
{
printf("文件打开失败!\n");
return;
}
char buf[64] = { 0 };
while ( fgets(buf,sizeof(buf),f1) )//只要读取到内容,进行循环
{
//printf("%s", buf);
int num1 = 0;
int num2 = 0;
char ch = 0;
//读取文件信息,拆分字符串
sscanf(buf, "%d %c %d =\n", &num1, &ch, &num2);
int ans = 0;
switch(ch)
{
case'+': ans = num1 + num2;
break;
case'-': ans = num1 - num2;
break;
case'*': ans = num1 * num2;
break;
case'/': ans = num1 / num2;
break;
}
//将结果写入新文件,拼接字符串
char msg[32] = { 0 };
sprintf(msg, "%d %c %d = %d\n", num1, ch, num2, ans);
fputs(msg, f2);
}
//关闭文件
fclose(f1);
fclose(f2);
printf("所有题目解答完毕!\n");
}
案例二:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NUM 100
void sortNum()
{
srand((size_t)time(NULL));
int i = 0;
int j = 0;//循环指标
int arr[NUM] = { 0 };//承载数组
//打开文件,写入随机数
FILE* f_write = fopen("随机数.txt", "w");
if (f_write == NULL)
{
printf("文件打开失败!\n");
return;
}
for (i = 0; i < NUM; i++)
{
fprintf(f_write, "%d\n", rand() % 1000 + 1);
}
//此时光标位于文件末尾
//方法一:先关闭再打开
fclose(f_write);
//方法二:当然还可以手动让光标置首
fseek(f_write, 0, SEEK_SET);
//方法三:直接调用置首函数
rewind(f_write);
//读取文件信息,写入数组
FILE* f_open = fopen("随机数.txt", "r");
if (f_open == NULL)
{
printf("文件打开失败!\n");
return;
}
for (i = 0; i < NUM; i++)
{
fscanf(f_open, "%d\n", &arr[i]);
}
//冒泡排序
for (i = 0; i < NUM - 1; i++)
{
for (j = 0; j < NUM - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
//将已排序的数组信息写入新文件
FILE* f_sort = fopen("排序后.txt", "w");
if (f_sort == NULL)
{
printf("文件打开失败!\n");
return;
}
for (i = 0; i < NUM; i++)
{
fprintf(f_sort, "%d\n", arr[i]);
}
//关闭文件
fclose(f_open);
fclose(f_sort);
}