下面这段代码:
#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;
}
}
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