静态外部变量和静态局部变量
linux中vi的替换用法

fstream用法

yichen posted @ 2014年2月20日 22:01 in Essay , 438 阅读

1

1

#include <iostream>
#include <fstream>
using namespace std;

ifstream fin;
ofstream fout;

int main()
{
   float x,y,z;
   
   fin.open("in.dat");
   if(!fin)
   {
       cout << "can not open the file:in.dat" << endl;
   }
   fin >> x >> y >> z;
   
   fout.open("out.dat");
   if(!fout)
   {
       cout << "can not open the file :out.dat"<< endl;
   }
   fout << x << " " << y << " " << z << endl;;
   
   fin.close();
   fout.close();
   
   return 0;
}

亦有形式:fstream fin/fout("filename");从而略去fin/fout.open("filename");

一、打开文件
  在fstream类中,有一个成员函数open(),就是用来打开文件的,其原型是:

void open(const char* filename,int mode,int access);

参数:

filename:  要打开的文件名
mode:    要打开文件的方式
access:   打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:

ios::app:   以追加的方式打开文件
ios::ate:   文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary:  以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in:    文件以输入方式打开
ios::out:   文件以输出方式打开
ios::nocreate: 不建立文件,所以文件不存在时打开失败 
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc:  如果文件存在,把文件长度设为0
  可以用“或”把以上属性连接起来,如ios::out|ios::binary

  打开文件的属性取值是:

0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件


  可以用“或”或者“+”把以上属性连接起来 ,如3或1|2就是以只读和隐含属性打开文件。

  例如:以二进制输入方式打开文件c:config.sys

  fstream file1;
  file1.open("c:\config.sys",ios::binary|ios::in,0);

  如果open函数只有文件名一个参数,则是以读/写普通文件打开,即:

  file1.open("c:\config.sys");<=>file1.open("c:\config.sys",ios::in|ios::out,0);

  另外,fstream还有和open()一样的构造函数,对于上例,在定义的时侯就可以打开文件了:

  fstream file1("c:\config.sys");

  特别提出的是,fstream有两个子类:ifstream(input file stream)和ofstream(outpu file stream),ifstream默认以输入方式打开文件,而ofstream默认以输出方式打开文件。

  ifstream file2("c:\pdos.def");//以输入方式打开文件
  ofstream file3("c:\x.123");//以输出方式打开文件

  所以,在实际应用中,根据需要的不同,选择不同的类来定义:如果想以输入方式打开,就用ifstream来定义;如果想以输出方式打开,就用ofstream来定义;如果想以输入/输出方式来打开,就用fstream来定义。

二、关闭文件
  打开的文件使用完成后一定要关闭,fstream提供了成员函数close()来完成此操作,如:file1.close();就把file1相连的文件关闭。

附:c语言代码

#include<stdio.h>

int main()
{
        FILE *p;
        int a[3] = {1,2,3};
        p = fopen("a.txt","w");
    if(!p)
    {
        printf("打开文件失败!\n");
        return;
    }
        for(int i=0;i<3;++i)
        {
            fprintf(p,"%d",a[i]);
        }
        fclose(p);
                                                                                                                                                                                                         
        return 0;
}
 

1


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter