c++ - How to return a vector of null terminated const char*? -


i trying read file, line-by-line. convert each line null terminated string. push lines vector , return it.

vector<const char*> typeglscene::loadglshader (string thisfile) { ifstream fromfile; fromfile.open(thisfile); if (fromfile.good()==false) {     cout<<"could not find file: "<<thisfile<<endl;     exit(1); }  vector<const char*>  filecontents; const char*    oneline; string         linestr;  while (fromfile.good()==true) {     getline(fromfile,linestr);     oneline = linestr.c_str();     filecontents.push_back(oneline); }  fromfile.close(); return filecontents; 

the problem char strings created in stack , function returns vector of char* nowhere.

i attempting allocate memory on heap by:

oneline = new char[linestr.size()+1]; 

but stuck, because once allocated cannot copy it; contents being const.

how on earth going use new keyword on const char* , add contents @ same time before realizes it's const ?

(not mention have delete them 1 one, on other side ... mess)

edit: rather return vector because don't know of quick (one line) way convert vector const char** for:

void glshadersource(gluint shader,                     glsizei count,                     const glchar **string,                     const glint *length); 

returning std::vector<char*> fraught problems.

  1. you'll have allocate memory each line. client of function must add code deallocate memory. client code becomes more complex needs be.

  2. the client function must know whether char* allocated using malloc or operator new. have follow appropriate method memory deallocation based on method used allocate memory. once again, client burdened knowing function , how it.

a better method return std::vector<std::string>.

std::vector<std::string>  filecontents; std::string linestr;  while (fromfile.good()==true) {     getline(fromfile,linestr);     filecontents.push_back(linestr); }  fromfile.close(); return filecontents; 

if must return std::vector<char*>, can use:

std::vector<char*>  filecontents; std::string linestr;  while (fromfile.good()==true) {     getline(fromfile,linestr);     char* line = new char[linestr.size()+1];     strcpy(line, linestr.c_str());     filecontents.push_back(line); }  fromfile.close(); return filecontents; 

Comments