C++ 文件读取一行

30534阅读 0评论2012-09-28 glinuxi
分类:C/C++

    对于熟悉C 语言的coder ,可能在C++的很多方面都有一点不适应。
   
    我今天的主要目的是实现一个从文件中按行读取,每行中不同的变量以空格分开。
    
实现代码:
  1. #include<map>
  2. #include<iostream>
  3. #include<fstream>
  4. #include<string>
  5. using namespace std;

  6. string src="/usr/local/";

  7. int read_mysql_xml(string &host,string &user,string &pass, string &dbname,int &port)
  8. {
  9.     ifstream readfile;
  10.     string line;
  11.     int count=5;
  12.     map<string ,string> infile;
  13.     
  14.     readfile.open(src.c_str(),ios::in);
  15.     
  16.     if(!readfile)
  17.     {
  18.         return 1; /*没有打开该文件*/
  19.     }
  20.     while(count--)
  21.     {
  22.         getline(readfile,line);
  23.         string::size_type index = line.find_first_of(" ",0);    
  24.         string first = line.substr(0,index);
  25.         string second = line.substr(index+1);
  26.         infile[first]=second;
  27.     }
  28.     host = infile["host"];
  29.     user = infile["user"];
  30.     pass = infile["pass"];
  31.     dbname = infile["dbname"];
  32.     port = atoi(infile["port"].c_str());
  33. }
错误:
error: no matching function for call to 'std::basic_ifstream >::basic_ifstream(std::string&)' 
是对于文件流初始化时的文件名传递的是 string 类型。

上一篇:跨域访问
下一篇:第一个有点效用的 shell 模板