下面这段代码:

 #include <iostream>

#include  < fstream >
using   namespace  std;

main()
{
    
char   *  filename  =  ( char   * )malloc( 40 );
    strcpy(filename,
" /home/admin/local/apache/logs/access_log " );
    ifstream ifs(filename);
    
    
if (ifs.good()){
        cout
<< " open success " << endl;
        
string  temp;
        getline(ifs,temp);
        cout
<< temp << endl;
    }   
}

注意标红的40,这个正是下面

/home/admin/local/apache/logs/access_log的长度,但是ifstream打开失败

把这个40改成41,问题解决!从这一点可以间断判断:

ifstream打开文件的时候,要求c-style的string后面一定要加上\0 


 

转载于:https://www.cnblogs.com/welkinwalker/archive/2011/07/12/2104050.html

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐