C++基础实例-文件Io等(5)

基本输入读取

#if 0
/*读写文件cin.getline*/
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<process.h>
using namespace std;
main()  {
    //声明变量
    FILE *fp1;
    char str[80];

    //从键盘上任意输入一个字符串
    cout<<"Inupt a string:";
    cin.getline(str,80);

    //以写入方式打开d.dat文件
    if ((fp1=fopen("d.dat","w"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    // 写"流"文件 
    fputs(str,fp1); 
    fputs("\n",fp1);

    fclose(fp1);            	//关闭文件

    // 以读方式打开d.dat文件
    if ((fp1=fopen("d.dat","r"))==NULL) 
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    // 循环从"流"文件读取字符,并显示
    char ch;
    while ((ch=fgetc(fp1))!=EOF)  
          cout<<ch;		
    cout<<endl;
    fclose(fp1); //关闭文件
}
#endif

cin>>写入

#if 0
/*cin>>*/
#include<iostream.h>
#include <process.h>
#include<stdio.h>
#include<conio.h>
void main(void)  {
    //变量声明
    char ch;
    FILE *fp1;

    //以写入方式打开d.dat文件 
    if ((fp1=fopen("d.dat","w"))==NULL)    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //循环从键盘上读取字符,写入"流"文件
    cout<<"char:"<<endl;
    cin>>ch; 
    while (ch!='*') {
        fputc(ch,fp1);   //将字符写到fp1指向的"流"文件中
        cin>>ch; 
    }
    fclose(fp1);  //关闭文件

    // 以读方式打开d.dat文件
    if ((fp1=fopen("d.dat","r"))==NULL) 
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    // 循环从"流"文件读取字符,并显示
    while ((ch=fgetc(fp1))!=EOF)  
          cout<<ch<<"  ";		
    cout<<endl;
    fclose(fp1); //关闭文件
}
#endif

stricmp()

#if 0
/*stricmp或strcmpi*/
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<process.h>
main()  {
    //声明变量
    int i=0;
    char p[100];   			// 声明输入缓冲区 
    FILE *fp1;     			// 声明文件指针变量

    //以写入方式打开d.dat文件
    if ((fp1=fopen("d.dat","w"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    // 写文件操作 
    for (i=1;;i++)  {            //无条件循环
        cout<<i<<" string:";
        cin>>p;         	      //从键盘上输入数据
        if (stricmp(p,"end")) {	  //如果输入的字符串为end,则结束循环
            fputs(p,fp1);         //写入文件操作
            fputs("\n",fp1); 
        }
        else
            break;                //退出循环
    }
 
    fclose(fp1);               	//关闭文件

    // 以读方式打开d.dat文件
    if ((fp1=fopen("d.dat","r"))==NULL) 
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    // 循环从文件读取字符,并显示
    while (fgets(p,100,fp1)!=NULL)  
          cout<<p;		
     fclose(fp1); //关闭文件
}
#endif

rand()-putw()

#if 0
/*rand与putw*/
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<process.h>
#include<stdlib.h>
#define MAX    10
main()  {
    //声明变量
    int i,n;
    FILE *fp1;     			// 声明文件指针变量

    //以写入方式打开d.dat文件
    if ((fp1=fopen("d.dat","w"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    // 写文件操作 
    for (i=1;i<=MAX;i++)  {     
        n=rand();        //产生1个整数随机数
        putw(n,fp1);//将整型n写入fp1指向的文件(d.dat)
        cout<<n<<" ";
    }
    cout<<endl<<"--------------------"<<endl;
 
    fclose(fp1);               	//关闭文件

    // 以读方式打开d.dat文件
    if ((fp1=fopen("d.dat","r"))==NULL) 
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }
  
    // 循环从"流"文件读取字符,并显示
    while ((n=getw(fp1))!=EOF)  
          cout<<n<<" ";	
		cout<<endl;

    fclose(fp1); //关闭文件
}
#endif

结构体、数组-文件

#if 0
/*fprintf-pscanf*/
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<process.h>
#include<stdlib.h>
#define MAX    3
main()  {
    //定义结构类型
    struct student {
        int num;
        char name[10];
        float grade;
    };

    //声明数组和变量
    student st[3];
    int i;
    FILE *fp1;     			    // 声明文件指针变量

    //以写入方式打开d.dat文件
    if ((fp1=fopen("d.dat","w"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //从键盘上读数据,写入文件
    cout<<"    num    name    grade"<<endl;
    for (i=0;i<MAX;i++)  {     
        cout<<i+1<<" ";
        cin>>st[i].num;
        cin>>st[i].name;
        cin>>st[i].grade;
        fprintf(fp1,"%d %s %f\n",st[i].num,st[i].name,st[i].grade);
    }
 
    fclose(fp1);               	//关闭文件

    // 以读方式打开d.dat文件
    if ((fp1=fopen("d.dat","r"))==NULL) 
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }
  
    // 循环从"流"文件读取字符,并显示
    student t;
    while ((fscanf(fp1, "%d %s %f",&t.num,t.name,&t.grade))!=EOF)  {
          cout<<t.num<<" ";		
          cout<<t.name<<" ";		
          cout<<t.grade<<endl;		
    }

    fclose(fp1); //关闭文件
}
#endif

二进制文件

#if 0
/*二进制文件*/
#include<iostream.h>
#include <process.h>
#include <stdlib.h> 
#include <stdio.h> 
int main(void) 
{ 
    FILE *fpd,*fpw;    // 声明FILE结构指针变量 
    unsigned char dw;
    int i=0;

    //以二进制读方式打开Calc.exe文件
    if((fpd=fopen("C:\WINDOWS\Calc.exe", "rb"))==NULL) 
    { 
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    } 

    // 以二进制写方式打开xc.exe文件 
    if((fpw=fopen("xc.exe", "wb+"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    // 二进制文件读写操作,每次指定读写1个字节
    while(!feof(fpd)) {   //使用feof()判断文件尾 
        fread(&dw, 1, 1, fpd);
        fwrite(&dw, 1, 1, fpw);
    }
    // 关闭文件
    fclose(fpd);
    fclose(fpw);

    //执行Calc.exe和Calc.exe文件
    cout<<"1 Run C:\WINDOWS\Calc.exe"<<endl;
    system("C:\WINDOWS\Calc.exe");
    cout<<"-------------------"<<endl;
    cout<<"2 Run xc.exe!"<<endl;
    system("xc.exe");
}
#endif

文件定位、偏移量

#if 0
/*文件定位、偏移量*/
#include<iostream.h>
#include <process.h>
#include<stdio.h>
#include<conio.h>
void main(void) 
{
    //声明变量
    int i;
    char ch;
    FILE *fp1;

    //以写入方式打开d.dat文件 
    if ((fp1=fopen("d.dat","w"))==NULL)    
	{
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //循环从键盘上读取字符,写入文件
    cout<<"char:";
    cin>>ch; 
    while (ch!='*') {
        fputc(ch,fp1);   //将字符写到fp1指向的"流"文件中
        cin>>ch; 
    }
    cout<<"--------------------"<<endl;
    fclose(fp1);  //关闭文件

    //以读方式打开d.dat文件
    if ((fp1=fopen("d.dat","r"))==NULL) 
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //循环从文件读取字符,并显示
    while ((ch=fgetc(fp1))!=EOF)  
          cout<<ch;		
    cout<<endl<<"--------------------"<<endl;

    //以下按倒序方式读取文件中的字符,并显示
    for (i=-1;;i--) {
        fseek(fp1,i,2);   			//设置文件指针,偏移量为i,相对文件尾
        if ((ch=fgetc(fp1))!=EOF)
            cout<<ch;
         else
            break;
    }
    cout<<endl<<"--------------------"<<endl;

    //以下读取"流"文件中偶数位置上的字符,并打印
    long position;
    for (i=0;;i=i+2) {
        fseek(fp1,i,0);        	//设置文件指针,偏移量为i,相对文件头
        position=ftell(fp1);//相对指针偏移量
        if ((ch=fgetc(fp1))==EOF)	 //遇到文件尾,则退出,否则打印读取的字符
            break;     
        else {
           cout<<position<<" :"<<ch<<endl;
        }
    }
    cout<<endl;

    fclose(fp1); //关闭文件
}
#endif

数组写入文件与读取

#if 0
/*数组写入文件与读取*/
#include<iostream.h>
#include<stdio.h>
#include<process.h>
#include<stdlib.h>
#define len 5

//显示数组的数据
void show_array(double x[],int size) {
    for(int i=0;i<size;i++)
        cout<<x[i]<<" ";
    cout<<endl;
}

//main函数测试数组数据的文件读写
int main(void) 
{ 
    //声明变量
    FILE *fp;    // 声明FILE结构指针变量 
    int i;
    double a[len]={1.0,1.2,1.4,1.6,1.8};

    //显示数组a的数据
    cout<<"a:";
    show_array(a,len);

    //打开d.dat文件
    if ((fp=fopen("d.dat","wb+"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //以单个元素对数组进行文件读操作
    for(i=0;i<len;i++) { 
        fwrite(&a[i], sizeof(double), 1, fp);
    }

    rewind(fp);   //恢复读写指针的位置

    //以单个元素对数组进行文件读操作
    double b[len];
    for(i=0;i<len;i++) { 
       if (!feof(fp))    //使用feof()判断文件尾 
         fread(&b[i], sizeof(double), 1, fp);
       else
            break;
    }
    cout<<"b:";
    show_array(b,len);//显示数组b的数据

    fclose(fp); // 关闭文件

    //打开d1.dat文件
    if ((fp=fopen("d1.dat","wb+"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //将数组当成数据块写入文件
    fwrite(&a, sizeof(double), len, fp);

    rewind(fp);   //恢复读写指针的位置

    //将数组当成数据块从文件中读取
    double c[len];
    if (!feof(fp))    //使用feof()判断文件尾 
         fread(&c, sizeof(double),len,fp);
    cout<<"c:";
    show_array(c,len);  //显示数组c的数据
    
    fclose(fp); // 关闭文件
}
#endif

struct写入与读取

#if 0
/*struct写入文件与读取*/
#include<iostream.h>
#include<stdio.h>
#include<process.h>
#include<stdlib.h>
#define len 5
//定义结构类型
struct student {
       int  num;
       char name[20];
       float grade;
};

//显示student结构数据
void show_str(student a,char *name) {
    cout<<name<<":"<<endl;
    cout<<a.num<<" "<<a.name<<" "<<a.grade;
    cout<<endl;
}

//main函数测试结构数据的文件读写
int main(void) 
{ 
    //声明变量
    FILE *fp;    
    //声明FILE结构指针变量 
    student st={1001,"TianRui",85.5};

    //显示st结构数据
    show_str(st,"st");

    //打开d.dat文件
    if ((fp=fopen("d.dat","wb+"))==NULL)
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //用fprintf()函数写结构数据到文件
    fprintf(fp,"%d %s %f",st.num,st.name,st.grade);

    rewind(fp);   //恢复读写指针的位置

    //用fscanf()函数读文件中的数据赋值给结构并显示
    student temp;
    fscanf(fp, "%d %s %f",&temp.num,temp.name,&temp.grade);
    show_str(temp,"temp");
    cout<<"-----------------------"<<endl;

    fclose(fp); // 关闭文件

    //将结构数据当成数据块进行读写
    if ((fp=fopen("dx.dat","wb+"))==NULL)  //打开dx.dat文件
    {
       cout<<"\nCould not open the file."<<endl;
       cout<<"Exiting program."<<endl;
       exit(1);   //结束程序执行
    }

    //声明结构数组并初始化
    int i;
    student starr[3]={{101,"XieCh",92},{102,"Li",85},{103,"TangXu",97}};

    //显示结构数组
    for(i=0;i<3;i++) 
        show_str(starr[i],"starr");

    //将结构数组当成数据块写入文件
    fwrite(starr, sizeof(student), 3, fp);

    rewind(fp);   //恢复读写指针的位置

    //按数据块从文件中读取数据赋值给结构数组
    student temp_arr[3];
    if (!feof(fp))    //使用feof()判断文件尾 
         fread(temp_arr, sizeof(student),3,fp);
    for(i=0;i<3;i++) 
        show_str(temp_arr[i],"temp_arr");
    
    fclose(fp); // 关闭文件
}
#endif

stdin-stdout

#if 0
/*stdin-stdout*/
#include<stdio.h>
#include<stdlib.h>
#include<iostream.h>
int main(void) 
{ 
    //声明变量
    char ch;
    char str[20];
    int n;
    float x;

    //用stdin从键盘上输入数据
    fprintf(stdout,"ch str\n");
    fscanf(stdin,"%c %s",&ch,str);
    fprintf(stdout,"n    x \n");
    fscanf(stdin,"%d  %f",&n,&x);
    cout<<"----------------"<<endl;

    //输出显示
    fprintf(stdout,"ch=%c str=%s",ch,str);
    fprintf(stdout,"\nn=%d x=%f",n,x);
    cout<<endl;
}
#endif

ferror-perror-clearerr

#if 0
/*ferror-perror-clearerr*/
#include <stdio.h>
void main( void )
{
    int c;
    /* Create an error by writing to standard input. */
    putc( 'A', stdin );
    if( ferror( stdin ) )
    {
      perror( "Write error" );
      clearerr( stdin );
    }

    /* See if read causes an error. */
    printf( "Will input cause an error? " );
    c = getc( stdin );
    if( ferror( stdin ) )
    {
       perror( "Read error" );
       clearerr( stdin );
    }
}
#endif

数学三角函数

#if 0
/*三角函数*/
#include<iostream.h>
#include<math.h>   //此预处理指令不可少(数学运算)
const double angle=3.1415926/180;
main() {
    cout<<"x\tsin(x)"<<endl;
    for (int i=0;i<=180;i=i+30) 
        cout<<i<<"\t"<<sin(i*angle)<<endl;
}
#endif

define

#if 0
/*define*/
#include<iostream.h>
//宏替换预处理指令
#define  YES        1
#define  PI         3.1415926
#define  DEG        PI/180
#define  MESG       "This is a string."

//以下是主程序 
main()  {
    //以下各语句使用了宏替换 
    cout<<"YES="<<YES<<endl;
    if (YES) 
       cout<<"PI="<<PI<<endl;
    cout<<"DEG="<<DEG<<endl;
    cout<<MESG<<endl;
}
#endif

带参数define

#if 0
/*带参数define*/
#include<iostream.h>
//带参数宏替换的预处理指令 
#define  PRINT(k)   cout<<(k)<<endl;
#define  MAX(a,b)   ((a)>(b) ? (a):(b))
main()
{
    int i=3,j=2;

    //MAX(a,b)宏替换的使用 
    cout<<"MAX(10,12)="<<MAX(10,12)<<endl;
    cout<<"MAX(i,j)="<<MAX(i,j)<<endl;
    cout<<"MAX(2*i,j+3)="<<MAX(2*i,j+3)<<endl;

    //PRINT(k)宏替换的使用
    PRINT(5);
    PRINT(MAX(7,i*j));   
}
#endif

#if--#endif

#if 0
/*#if-#endif,在实例(1)已大致描述*/
#include<iostream.h>
#define   PI   3.1416
main()  
{
    int i=100;
#if 1
    cout<<"i="<<i<<endl;
#endif

#ifdef PI
    cout<<"1  PI="<<PI<<endl;
#endif

#ifndef PI
    cout<<"2  PI="<<PI<<endl;   //此语句不被编译执行,类似于注释
#endif
}
#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Swxctx

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值