开发者

is there any function in c++ to check whether a file given in a specific path is a script(.sh) file or not

开发者 https://www.devze.com 2023-04-09 02:38 出处:网络
there is .sh file in one of the directories for eg:path = /opt/WD/CD/SCD/temp.sh is there any function is c++ to check whether file in that location(path) is a script(.sh) file or not

there is .sh file in one of the directories for eg: path = /opt/WD/CD/SCD/temp.sh

is there any function is c++ to check whether file in that location(path) is a script(.sh) file or not

bool ValidCommand(const string & path)
{
bool r开发者_高级运维eturn = true;

    {
    if (!access(path.c_str(),X_OK))
    {
        return = true;
    }
    else
        return = false;
 }

path = /opt/WD/CD/SCD/temp.sh

access is not working for me:(


Have a look at

  • stat -- to check the executable bit
  • libmagic -- to detect file type from (a.o.) the hash-bang line


Maybe stat does what you need, otherwise you can look at the source for file and see how it does it.


You can use stat. If it failed (returned -1), the file doesn't exist.


Just how precise do you want it. It's fairly straightforward to read the directory and look for filenames ending in .sh. (boost::filesystem has everything you need for that.) But of course, I could name my C++ headers file.sh if I wanted (and was a bit perverse). A considerably more accurate test would involve reading the start of the file: if the first two bytes are "#!", it's probably a script of some sort, and if the first line matches "#!\\s*(?:/usr)?/bin/sh/[a-z]*sh", then you're almost sure it's a shell script. Drop the [a-z]*, and it's a Bourne or a Posix shell script.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号