【C++】读取文件

 

包含头文件ios

#include<fstream>(不带扩展名“.h“)app

读写文件:ifstream(读)、ofstream(写)、fstream(读写):#include<ifstream>;#include<ofstream>;#include<fstream>,分别从istream、ostream、iostream中引伸而来的,因此fstream的对象能够使用其父类成员来访问数据。函数

获取文件名spa

geetline(cin,filename,‘\n’);方式获得用户输入的用户名,其中filename为String类型;与同控制台(console)交互一样的成员函数(cin&cout)来进行输入输出。.net

#inclulde<iostream>
#include<fstream>//文件头文件
#include<String>

int main()
{
ifstream in;//ifstream读文件
string filename;//文件名
getline(cin, filename, '\n');//获取文件名,也能够使用cin>>filename;可是不能获取空格

in.open(filename);

if(!in)//或if_open()
{
cerr<<"打开文件出错"<<endl;
return 1;
}

//逐个读取字符
char ch;
while(!in.eof())//到达文件尾时返回true
{
in.read(&ch, 1);
cout<<ch;
}

in.close();//必须关闭文件
}
ofstream out("out.txt");  
     if (out.is_open())   
    {  
         out << "This is a line.\n";  
         out << "This is another line.\n";  
         out.close();  
     }  
 char buffer[256];  
       ifstream in("test.txt");  
       if (! in.is_open())  
       { cout << "Error opening file"; exit (1); }  
       while (!in.eof() )  
       {  
           in.getline (buffer,100);  
           cout << buffer << endl;  
       }  

open函数code

<span style="font-family:Times New Roman;font-size:16px;">  
public member function  
  
void open ( const char * filename,  
            ios_base::openmode mode = ios_base::in | ios_base::out );  
  
void open(const wchar_t *_Filename,  
        ios_base::openmode mode= ios_base::in | ios_base::out,  
        int prot = ios_base::_Openprot);  
  
</span>  

参数对象

filename 操做文件名
mode 打开文件的方式
prot 打开文件的属性

在ios类中文件的打开方式blog

ios::in 为输入(读)而打开文件
ios::out 为输出(写)而打开文件
ios::ate 初始位置:文件尾
ios::app 全部输出附加在文件末尾
ios::trunc 若是文件已经存在则先删除已存在文件
ios::binary 二进制方式

方式能够使用”|“来隔开进行组合使用:in(”文件名.txt“, ios::in | ios::out | ios::binary);ci

ios类中打开文件的属性定义get

0 普通文件,打开操做
1 只读文件
2 隐含文件
4 系统文件

属性能够使用”+“来隔开进行组合使用

使用open默认方法(直接对流对象进行文件操做)

<span style="font-family:Times New Roman;font-size:16px;">  
ofstream out("...", ios::out);  
ifstream in("...", ios::in);  
fstream foi("...", ios::in|ios::out);  
  
</span>  

标志性验证(bool)

bad():过程当中出错,返回true,如设备已满

fail():在bad的功能基础上,加上格式错误时也返回true

eof()

good():以上函数返回true时,函数返回false

(重置成员函数所检查的状态标志,使用 .clear())

参考:【http://blog.csdn.net/kingstar158/article/details/6859379/