C++中的文件和文件夹操作

File and Folder Operations in C++

本文关键字:文件夹 操作 文件 C++      更新时间:2023-10-16

我正在用C++编写一个todo列表管理器程序,并希望执行以下操作:

  1. 检查程序的工作目录中是否存在目录,如果不创建该目录
  2. 如果它确实存在,请从中获取.txt文件列表
  3. 能够从此目录创建/删除.txt文件

我尝试过使用boost/filesystem.hpp,但似乎不明白(或者如何使用g++将其链接)。下面是我尝试过的一个例子(假设正确的#includesint main等):

std::vector<std::string> findLists(void){
    std::vector<std::string> lists;
    std::string temp;
    char dir[ MAX_PATH ];
    std::string(dir, GetModuleFileName(NULL, dir, MAX_PATH));
    dir = dir.substr(0,dir.find_last_of( "\/" ));
    path p(dir);
    for(auto i = directory_iterator(p); i != directory_iterator(); i++){
        if(!is_directory(i->path())){
            temp = i->path().filename().string();
            if(temp.compare(0,temp.find(".")+1,".txt")){
                temp = temp.substr(0,temp.find("."));
            }
            lists.push_back(temp);
        }
        else{
            continue;
        }
    }
    return lists;
}

来自Boost文档

int main(int argc, char* argv[])
{
  path p (argv[1]);   // p reads clearer than argv[1] in the following code
  if (exists(p))    // does p actually exist?
  {
    if (is_regular_file(p))        // is p a regular file?   
      cout << p << " size is " << file_size(p) << 'n';
    else if (is_directory(p))      // is p a directory?
      cout << p << "is a directoryn";
    else
      cout << p << "exists, but is neither a regular file nor a directoryn";
  }
  else
    cout << p << "does not existn";
  return 0;
}

那里有你需要的所有设施。这只是一个起点,但你应该能够很快度过难关。