21xrx.com
2024-06-03 06:49:36 Monday
登录
文章检索 我的文章 写文章
C++编写获取指定文件所在目录的类
2023-07-05 07:24:18 深夜i     --     --
C++ 获取文件目录

在C++编程中,获取指定文件所在目录是一项常见的操作。为了实现这个需求,我们可以编写一个类来完成。该类的作用是输入指定的文件路径,然后返回该文件所在的目录路径。下面是一个简单的C++类实现示例:


#include <string>

#include <iostream>

#include <fstream>

#include <stdlib.h>

using namespace std;

class GetDirPath {

public:

  string GetFilePath()

    return m_FilePath;

  

  void SetFilePath(string filePath)

    m_FilePath = filePath;

  

  string GetDirPath() {

    string::size_type pos = m_FilePath.find_last_of('/');

    if (pos == string::npos) {

      cerr << "Error: invalid file path" << endl;

      exit(1);

    }

    return m_FilePath.substr(0, pos);

  }

private:

  string m_FilePath;

};

int main() {

  GetDirPath dirPath;

  string filePath;

  cout << "Please input the file path:" << endl;

  getline(cin, filePath);

  dirPath.SetFilePath(filePath);

  cout << "The directory path of the file is:" << endl;

  cout << dirPath.GetDirPath() << endl;

  return 0;

}

上述代码的思路很简单,首先通过输入获取到指定文件的路径,然后将路径传递给GetDirPath类的SetFilePath方法。接着,GetDirPath类会扫描路径中最后一个斜杆之前的字符串,并返回剩余的字符串作为目录路径。

需要注意的是,如果输入的文件路径无效,程序会打印错误消息并退出。此时,开发者需要检查文件路径是否正确,并重新运行程序。

总的来说,通过编写一个获取指定文件所在目录的C++类,我们可以快速有效地实现我们的需求,并且可以在需要的项目中重复使用。同时,这个类也提供了一个很好的C++编程示例,可以帮助开发人员更深入地了解C++的基本语法和特性。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复