简体   繁体   中英

Run a few command line commands from c++

I wrote a program in python that has the functionality of being able to find out file sizes, create directories, and move around as though i'm just in a regular shell. The porblem is that I need to be able to do this in c++.

Here's the python code that I need c++ functionality from:

os.chdir('r'+str(r)+'n'+str(n))
def build_path(newpath):
    if os.path.isdir(newpath):
        os.chdir(newpath)
    else:
        os.mkdir(newpath)
        os.chdir(newpath)

And also this piece:

if os.stat('data'+str(tick)).st_size > 2500000:
    heavyFile.close()
    tick+=1
    heavyFile=open('data'+str(tick),'w')
os.system('touch COMPLETED'+str(r)+str(n))

So basically I need to be able to make some directories, change into those directories, build files, but don't let them get much larger than 2.5 MB, and when they finally get over that size, create a new file that is incremented by one.

so the file tree ends up looking like:

r4n4/dir1/data0,data1,data2,etc r4n4/dir2/data0,data1,data2,etc and so on.

How can I do this in c++? I know I can call system('command') but I don't know how to get file size nicely using that and I'm just hoping for an easier way to do this. Also, I do not have access to boost where I am running this program.

Try checking out the boost::filesystem library. ( http://www.boost.org/doc/libs/1_54_0/libs/filesystem/doc/index.htm ) All three of your requests are covered in the tutorial.

You can make use of system calls to achieve what you want. If you are on Linux, check out the following man pages:

man 2 chdir
man 2 mkdir
man 2 stat

You can use stat() in your code to get properties of filesystem objects. Here's an example:

#include <sys/types.h>
#include <sys/stat.h>

struct stat buf;
stat(filename, &buf);

// If it's a regular file, print the size in bytes
if ((buf.st_mode & S_IFREG) == S_IFREG)
{
  off_t size = buf.st_size;
  fprintf(stdout, "%s is a regular file\n", filename);
  fprintf(stdout, "%s is a regular file: size %zd bytes\n", filename, size);
}

There are also macros within stat.h which make it a little easier to check if something is a regular file or whatever, instead of AND'ing multiple things as above. For example, the S_ISREG macro will do the same thing as the code above:

if(S_ISREG(buf.st_mode))   /* stat.h macro, instead of AND'ing */
{
  fprintf(stdout, "%s is a regular file\n", filename);
}

The macro S_ISDIR would tell you if it's a directory. There are other macros like this.

You can do man -s 2 stat to see the man page for stat() and get more details. Hope this helps.

您也可以使用以下命令从c ++代码中调用脚本:

system ("python script.py");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM