Home > Blockchain >  How to get parent folder from path in C
How to get parent folder from path in C

Time:07-09

I am using C in linux and I want to extract the parent folder from a path in C 14.

For example, I have the path likes

/home/abc/fi.mp4

My expected output be abc. How can I do it in C

This is that I did


std::string getFolderName(const std::string &path) {
  size_t found = path.find_last_of("/\\");
  string foldername = ...
  return foldername;
}

CodePudding user response:

You probably want something like this:

std::string getFolderName(const std::string &path) {
   const size_t found = path.find_last_of("/\\");
   return (found == string::npos) ? path : path.substr(0, found);
}

CodePudding user response:

I believe the experimental version of std::filesystem was already available in C 14.
If it is indeed available in your environment, you can use parent_path() to get the parent folder from a path:

#include <string.h>
#include <iostream>
#include <experimental/filesystem>

int main(int argc, char const* argv[])
{
    std::experimental::filesystem::path p = "/home/abc/fi.mp4";
    std::experimental::filesystem::path parent_p = p.parent_path();
    std::cout << parent_p << std::endl;
    return 0;
}

You can further use parent_path() to climb up the hirarchy.
In order to convert a path to std::string you can use the string() method.

Once C 17 is available for you, you can simply drop the experimental prefix.

CodePudding user response:

The function getFolders will get you all the folder names in a path.

#include <vector>
#include <iostream>
#include <string>
using namespace std;

vector<string> getFolders(const char* path) {
    vector<string> folders;
    int i = 0,k=0;
    char c;
    char buffer[256];
    
    while ((c = *(path   i)) != '\0') {
        if (c != '/') {
            buffer[k  ] = c;
        } else {
            if (k > 0){
                buffer[k] = '\0';
                folders.push_back(string(buffer));
                k = 0;
            }
        }
          i;
    }
    return folders;
}
void main()
{
    vector<string> folders = getFolders("/home/abc/fi.mp4");
    for (auto f : folders){
        cout << f << endl;
    }
}
  • Related