[c++] 파일 확장자 추출
다음은 확장자 추출을 위한 간단한 C++ 코드입니다.
#include <iostream>
#include <string>
std::string getExtension(const std::string& filename) {
size_t position = filename.rfind('.');
if (position != std::string::npos) {
return filename.substr(position + 1);
}
return "";
}
int main() {
std::string filename = "example.txt";
std::string extension = getExtension(filename);
if (extension.empty()) {
std::cout << "확장자가 없습니다." << std::endl;
} else {
std::cout << "확장자: " << extension << std::endl;
}
return 0;
}
위 코드에서 getExtension
함수는 파일 이름에서 마지막 점(.)의 위치를 찾은 후 그 뒤의 문자열을 추출하여 확장자로 반환합니다. 만약 점(.)의 위치를 찾지 못하면 빈 문자열을 반환합니다. main
함수에서는 예시 파일 이름을 이용하여 확장자를 추출하고 출력합니다.
이 코드를 실행하면 “txt”가 출력됩니다.
참고 문헌:
- https://en.cppreference.com/w/cpp/string/basic_string/find
- https://en.cppreference.com/w/cpp/string/basic_string/rfind