所以,我正在为我的 C++ 课程做一个项目。我正在制作音乐播放器,但从文件夹中读取时遇到了一些问题。我目前正在从文本文件中读取歌曲名称,但我想从文件夹中的文件中读取名称。旧代码:
std::vector<Song>tempHold;
string songNames;
string fileName = resourcePath()+"songsFile.txt";
std::ifstream dataIn;
//int wantedSongs = 16;
dataIn.open(fileName.c_str());
if(dataIn.is_open())
{
while(getline(dataIn,songNames))
{
tempHold.push_back(Song(songNames,"Taylor Swift"));
amount++;
}
}else{
std::cout << "error opening file";
return tempHold;
}
不起作用的新代码(这是我需要帮助的代码)
std::vector<Song>addSongsDir(int &amount)
{
std::vector<Song>tempHold;
string aLine;
string songNames;
string fileName = "/Users/adambjorkman/Desktop/testmusik";
DIR * songDir;
songDir = opendir(fileName.c_str());
while(readdir(songDir))
{
tempHold.push_back(Song(songNames,""));
std::cout << songNames;
}
}
我现在又试了一次
std::vector<Song>addSongsDir(int &amount)
{
std::vector<Song>tempHold;
string aLine;
string songNames;
string fileName = "/Users/adambjorkman/Desktop/testmusik";
DIR * songDir;
songDir = opendir(fileName.c_str());
struct dirent *songDirent;
if(songDir == NULL)
{
throw " No such directory";
}
else
{
while((songDirent = readdir(songDir)))
{
songNames = songDirent->d_name;
tempHold.push_back(Song(songDirent->d_name,""));
std::cout << songNames;
}
}
return tempHold;
}