C++从文件中读写的例子及产生随机数的例子

//例子1:这个函数是从文件中读取数据,然后将结果写到文件中
#include<cstdio>
 
 
//#include<cstdlib>
int main()
{
	FILE *fp1=fopen("data.txt","r");
	FILE* fp2=fopen("data.txt","w");
	
	if(fp1==NULL || fp2==NULL)
	{
		printf("file can not open!");
	}
	
	for(int i=0;i<100000;i++)
	{
		fprintf(fp2,"%d\n",i);
	}
	
	fclose(fp2);
	
	for(int i=0;i<100000;i++)
	{
		int temp;
		fscanf(fp1,"%d",&temp);
		printf("%d\n",temp);
	}
	
	fclose(fp1);	
	return 0;
}
 
 
//例子二:输入输出重定向:


/*函数名:freopen 
声明:FILE *freopen( const char *path, const char *mode, FILE *stream ); 
所在文件: stdio.h 
参数说明: 
path: 文件名,用于存储输入输出的自定义文件名。 
mode: 文件打开的模式。和fopen中的模式(如r-只读, w-写)相同。 
stream: 一个文件,通常使用标准流文件。 
返回值:成功,则返回一个path所指定文件的指针;失败,返回NULL。(一般可以不使用它的返回值) 
功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。 


        下面以在VC下调试“计算a+b”的程序举例。 
C语法: */
/*#include <stdio.h> 
int main() 
{ 
int a,b; 
freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取 
freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中 
while(scanf("%d %d",&a,&b)!=EOF) 
printf("%d\n",a+b); 
fclose(stdin);//关闭文件 
fclose(stdout);//关闭文件 
return 0; 
} */

//C++语法 
#include <stdio.h> 
#include <iostream> 
using namespace std;
int main() 
{ 
int a,b; 
freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取 
freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中 
while(cin>>a>>b) 
cout<<a+b<<endl; // 注意使用endl 
fclose(stdin);//关闭文件 
fclose(stdout);//关闭文件 
return 0; 
} 
        /*freopen("debug\\in.txt","r",stdin)的作用就是把标准输入流stdin重定向到debug\\in.txt文件中,这样在用scanf或是用cin输入时便不会从标准输入流读取数据,而是从in.txt文件中获取输入。只要把输入数据事先粘贴到in.txt,调试时就方便多了。 
类似的,freopen("debug\\out.txt","w",stdout)的作用就是把stdout重定向到debug\\out.txt文件中,这样输出结果需要打开out.txt文件查看。 

        需要说明的是: 
        1. 在freopen("debug\\in.txt","r",stdin)中,将输入文件in.txt放在文件夹debug中,文件夹debug是在VC中建立工程文件时自动生成的调试文件夹。如果改成freopen("in.txt","r",stdin),则in.txt文件将放在所建立的工程文件夹下。in.txt文件也可以放在其他的文件夹下,所在路径写正确即可。 
        2. 可以不使用输出重定向,仍然在控制台查看输出。 
        3. 程序调试成功后,提交到oj时不要忘记把与重定向有关的语句删除。*/

//例子三:C语言产生随机数的例子
/*你会发现程序连续执行N次的结果是一样的,这是因为如果未设置随机数种子,rand()在调用时会默认随机数种子为1。
为了解决这个问题C提供了srand()函数。所以在调用rand()产生随机数之前必须调用srand()设置种子。srand()的原形是void srand(int a)。
*/

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
	//函数原型: void __cdecl srand(unsigned int _Seed);
     srand((int)time(0));
     int i;
     for (i=0;i<10;i++)
     {
     	//函数原型:int __cdecl rand(void); 产生m到n之间的整数 
        printf("%d ",rand()%(n-m+1)+m);
      }
    
      printf("\n");
}

/*要让随机数限定在一个范围,可以采用模除加加法的方式。
要产生随机数r, 其范围为 m<=r<=n,可以使用如下公式:
rand()%(n-m+1)+m
其原理为,对于任意数,
0<=rand()%(n-m+1)<=n-m
于是
0+m<=rand()%(n-m+1)+m<=n-m+m
即
m<=rand()%(n-m+1)+m<=n*/


 
 
 
 
 

猜你喜欢

转载自blog.csdn.net/dh2442897094/article/details/78238922