c++文件的读取

来源:互联网 发布:网络高清数字矩阵 编辑:程序博客网 时间:2024/06/05 15:03

需要包含的头文件<fstream>

以下只列出核心代码,其它基本头文件自己添加

需要注意不管是读文件或者是写问件,结束后都要调用:   文件.clear()清除所有的标志位,文件.close()关闭文件

读文件流:

例如打开桌面的1.txt文件并读取数据

1.单个读取:

ifstream ifen;

char str[50];

ifen.open("C:\\Users\\lai\\Desktop\\1.txt");            

ifen>>str;

cout<<str<<endl;


2.按行读取:

ifstream ifen;

string buffer;

char str[50];

ifen.open("C:\\Users\\lai\\Desktop\\1.txt");

while(ifen.is_open())//判断文件是否已经打开

{

    getline(ifen,buffer);

    //也可以

   //ifen.getline(str,50);

   //cout<<str<<endl;

  cout<<buffer<<endl;              

}


//如果按行读入的文件每行是( Bob,Dog)这样的布局则可以使用下面的方法来分别读取Bob和Dog

//故分别定义以下两个函数用于提取一个string类型的字符串中想要的字符串

string getfname(string fname)
{
    string r;
    size_t index = fname.find(',');//获取逗号所在的位置
    if (index != -1)
        r = fname.substr(0, index); //从0位置开始到index位置前面取字符串
    else
        r = "-1";
    return r;
}

string getlname(string lname)//类似上面的函数
{
    string r;
    size_t index = lname.find(',');
    if (index != -1)
        r = lname.substr(index+1, lname.length()-1);
    else
        r =" -1";
    return r;
}

//即如果字符串str="Bob,Dog"则通过getfname(str)可以提取出Bob,同理用getlname(str)可以提取出Dog字符




写文件流:

string str=",";

vector<int>v;

int dim[]={1,2,3,4,5,6,7,8,9};

v.assign(dim.dim+9);

ofstream of("C:\\Users\\lai\\Desktop\\1.txt",ios::app);

of <<endl<< "开始写入数据"<<endl;

copy(v.begin(), v.end(), ostream_iterator<int> (of, str.c_str()));



从文件中读取中文和英文的混合字符

                                                  
#include<fstream>
#include <string>
#include <iostream>
using namespace std;
//假如一个文本文件ljl.txt中有如下的两行字符
//1300710216,李经理,20,男,qq,
//130071027,请问饿,21,男,ww,

int main()
{
    ofstream write_file("ljl.txt",ios::out|ios::app);//以写的方式打开文件,并且是在末尾追加(保证不会清空原本文件中的数据)
    while(write_file.is_open()&&!write_file.eof());//文件已经打开并且为读到末尾
   {
       string s,t;
       getline(write_file,s);//按行读取并且存储在s中
       //从s中读取,每次按照逗号分离出来的内容
       for(int i=0; i<s.length(); i++)
       {
            if(s[i]<255&&s[i]>0&&s[i]!=',')//表示该字符是ASCII类型 ,表示占一个字节
            {
               t.append(s.substr(i,1));   //.substr(one,two)第一个参数表示开始的位置,第二个表示位移的步数
            }
           else if((s[i]<0||s[i]>255)&&s[i]!=',')//表示该字符是unicode类型,表示占两个字节
            {
               t.append(s.substr(i,2));
               ++i;
            }

          if(s[i]==',')//按照逗号分离出s中的元素
            {
             cout<<t<<endl;
             t="";
            } 
      }
      
   }
    return 0;
}


个人笔记有待改善、、、、、、、

0 0
原创粉丝点击