I’ve a very simple function that should read a txt file and return all lines by one vector of the type string. I’ve stepped trough it quite a few times with the debugger and the only thing i’ve noticed is that the value of “fileName” changes on the line of the ifstream declaration. What am i doing wrong?? Thx.
vector<string> readFile(char* fileName)
{
vector<string> fileLines;
fileLines.clear();
string line;
ifstream myfile (fileName);
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
fileLines.push_back(line);
}
myfile.close();
}
return fileLines;
}
//////////////////////////////////
I have this function that should return the filenames of all txt files in the current directory.
vector<char*> getFileList()
{
vector<char*> fileNames;
fileNames.clear();
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
char currentPath[_MAX_PATH];
getCurrentPath(currentPath);
strncat(currentPath, "\\*", 3);
if (hFind = FindFirstFile(currentPath, &FindFileData))
{
string fileExtension = getExt(FindFileData.cFileName);
if (fileExtension == "txt" || fileExtension == "TXT")
{
fileNames.push_back(FindFileData.cFileName);
}
while(FindNextFile(hFind, &FindFileData) != 0)
{
string fileExtension = getExt(FindFileData.cFileName);
if (fileExtension == "txt" || fileExtension == "TXT")
fileNames.push_back(FindFileData.cFileName);
}
}
return fileNames;
}
That’s how the function is going to be called:
vector<char*> inputFileList = getFileList();
if (inputFileList.size() > 0)
{
for (int a=0; a<inputFileList.size(); a++)
{
fileLines = readFile(inputFileList[a]);
}
}
My bet would be that you get your filename from a function which returns a pointer to a local variable, e.g. something like this:
The above isn’t valid –
Filenamecontents are on stack, and will be invalidated whengetFilename()returns.vector<string> fileLines;will be located in the same memory, and therefore the datafileNamepoints to will change when you step over thevectorconstructor.EDIT: See e.g. C++ compiler warning – returning local variable for more information on this