1. 程式人生 > >[C/C++]_[初級]_[使用C字串(或者std::string)處理函式獲取檔案所在目錄

[C/C++]_[初級]_[使用C字串(或者std::string)處理函式獲取檔案所在目錄

//1.使用C字串處理函式獲取檔案所在目錄。

//2.使用std::string處理函式獲取檔案所在目錄。

//練習

//例如:檔案路徑:E:\software\practices\aa.png

//    目錄:輸出  E:\software\practices\

#include <string>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;

int main(int argc, char const *argv[])
{
        //string
        string str = "E:\\software\\practices\\aa.png";//注意:檔案路徑要寫成雙斜槓
	cout << "str: " << str << endl;
	string res = str.substr(0,str.find_last_of('\\')+1);
	cout << "res: " << res << endl;

	//C語言
	char* temp = strdup(str.c_str());
	char* c_str =  strrchr(temp,'\\');
	if(c_str)
	{
		*(c_str+1) = 0;
	}
	cout << "temp: " << temp << endl;

	return 0;
}
檔案路徑中雙斜槓和單斜槓的問題
http://blog.sina.com.cn/s/blog_6646924501017jyl.html