C++标准库 之 iostream库的学习笔记(三) ifstream类的使用和介绍

该继续看ifstream类了。

ifstream继承自istream类,istream类只有一个iostream库中创建好的cin对象,对应一个输入设备就是pc机的键盘,而ifstream类则没有在fstream中有创建好的对象,原因上一篇文章已经说了。

ifstream是文件输入类,输入的源是文件,目标是内存,从文件向内存输入,也就是读取文件的意思了。

如果想读取一个文件,简单的示例代码如下:

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

int  _tmain( int  argc, _TCHAR *  argv[])
{

    ifstream hFileRead(
"c:\\1.txt", ios::in, _SH_DENYRW); // denies read and write

    
if (!hFileRead)
    
{
        cout 
<< "read fail!" << endl;
        exit(
1);
    }


    
char ch;
    
string content;
    
while (hFileRead.get(ch)) // the get method retuan false on read end
    {
        content 
+= ch; // string support oprator+=, use overload
        cout.put(ch);    
    }

    system(
"pause"); // other process can't read or write the file
    hFileRead.close();
    system(
"pause"); 

    
return 0;
}


get方法会读取一个字符,当读到文件末尾就会返回false。
并且示例了_SH_DENYRW的共享方式打开文件的后果,在第一个暂停处无法打开c:\1.txt,当调用close才可以正常打开。

主要工作函数:
get
getline
read

另外有几个辅助函数:
peek
putback
ignore
gcount
seekg
seekdir
tellg

实际开发过程中使用std::getline这个全局函数来获取一行字符,使用如下:


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

int  _tmain( int  argc, _TCHAR *  argv[])
{
    fstream hFile;
    hFile.open(
"c:\\1.txt", ios::out | ios::in,  _SH_DENYWR); //only deny write
    
    
string str;
    
while(std::getline(hFile, str))
    cout 
<< str << endl;
    hFile.close();

    cin.
get();

    
return 0;
}

你可能感兴趣的:(iostream)