C++/C++심화

[C++]12. C++ 소스코드에서 linux 명령어 실행 하는 방법

뼈민 2019. 10. 20. 16:07
반응형

 

 

[C++]12. C++ 소스코드에서 linux 명령어 실행 하는 방법

 

 

안녕하세요 고급개발자가 꿈인 코린이 입니다.

 

오늘은 C++ 소스코드에서 linux 명령어를 실행하는 방법에 대해서 설명 드리겠습니다.

 

가끔 코딩을 하다보면 directory를 만들거나 파일은 만들어줄때가 있는데요 

 

이러한 것을을 쉽게 하기위해서 명령어들을 입력해서 실행할수 있도록 하는 하는 c++ 표준 라이브러리가 있습니다.

 

바로 system이라는 함수 인데요

 

이함수를 이용해서 매개변수에 string 형식으로 리눅스 명령어를 적으면 리눅스 명령어들을 실행할수가 있습니다.

 

아래의 코드를 보겠습니다.

 

ServiceClass.hpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#ifndef SERVICECLASSCECLASS_H
#define SERVICECLASSCECLASS_H
 
#include <iostream>
#include <vector>
 
class ServiceClass
{
public:
    ServiceClass();
    virtual ~ServiceClass();
 
private:
    int mValue1;
    int mValue2;
public:
   void makedirectory();
   void deletedirectory();
 
};
 
#endif // SERVICECLASSCECLASS_H
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

ServiceClass.cpp

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "ServiceClass.h"
 
ServiceClass::ServiceClass()
{
    makedirectory();
 
}
ServiceClass::~ServiceClass()
{
    
}
 
void ServiceClass::makedirectory()
{
    std::system("mkdir /home/shin/cpptest/makedirectory");
}
 
void ServiceClass::deletedirectory()
{
    std::system("rm -rf  /home/shin/cpptest/makedirectory");
}
 
 
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

실행하기전 

소스코드 실행전 터미널

 

 

 

위의 소스코드를 보시면 system을 이용해서 디텍토리를 만드는 명령어를 적어서 넣어주었습니다.

 

그 이후 위의 소스코드를 실행 시키면 생성자에서 makedirectory 함수를 호출해줌으로써 디렉토리가 만들어지는 것을 

 

확인할수 있습니다.

 

소스코드 실행 후 터미널

 

그래서 위와 같이 리눅스 명령어가 필요하거나 특정한 동작을 해야할때는 c++ 표준 라이브러리인 system을 이용해서

 

구현하시면 됩니다.

 

여기까지 읽어주셔서 감사합니다.!

 

 

반응형