1. 程式人生 > >C語言中linux下檢視sd卡mount的位置

C語言中linux下檢視sd卡mount的位置

linux 查詢sd卡mount的位置:
#include<sstream> //std::istringstream
#include<stdio.h> //FILE and popen
#include<string>
......其他標頭檔案......


std::string getSDCardPath();
主函式(getSDFCardPath);
......其他函式......
std::string getSDCardPath()
{
FILE *fp;
char buffer[80];
std::string str;
std::string tmpPath[3];
if((fp = popen("mount|grep /dev/sdcard",r)) == NULL)
std::cout << "failed" << std::endl;
//呼叫shell, r表示讀,其中/dev/sdcard 是系統預設的sd卡的名字,也有可能是mmcblk0,mmcblk0p1
fgets(buffer,sizeof(char)*80,fp);//從fp中取出80個字到buffer中
std::string str(buffer);
std::istringstream iss;//按空格切分string 
for(int i = 0;i != 3;++i)
{
iss >> tmpPath[i];
}


return tmpPath[2];
}
說說popen函式:


FILE * popen ( const char * command , const char * type );
int pclose ( FILE * stream );
popen() 函式通過建立一個管道,呼叫 fork 產生一個子程序,執行一個 shell 以執行命令來開啟一個程序。這個程序必須由 


pclose() 函式關閉,而不是 fclose() 函式。pclose() 函式關閉標準 I/O 流,等待命令執行結束,然後返回 shell 的終止狀


態。如果 shell 不能被執行,則 pclose() 返回的終止狀態與 shell 已執行 exit 一樣。
type 引數只能是讀或者寫中的一種,得到的返回值(標準 I/O 流)也具有和 type 相應的只讀或只寫型別。如果 type 是 "r" 


則檔案指標連線到 command 的標準輸出;如果 type 是 "w" 則檔案指標連線到 command 的標準輸入。
command 引數是一個指向以 NULL 結束的 shell 命令字串的指標。這行命令將被傳到 bin/sh 並使用-c 標誌,shell 將執行


這個命令。
popen 的返回值是個標準 I/O 流,必須由 pclose 來終止。前面提到這個流是單向的。所以向這個流寫內容相當於寫入該命令


的標準輸入;命令的標準輸出和呼叫 popen 的程序相同。與之相反的,從流中讀資料相當於讀取命令的標準輸出;命令的標準


輸入和呼叫 popen 的程序相同。
函式的返回值:
如果呼叫 fork() 或 pipe() 失敗,或者不能分配記憶體將返回NULL,否則返回標準 I/O 流。
popen 沒有為記憶體分配失敗設定 errno 值。
如果呼叫 fork() 或 pipe() 時出現錯誤,errno 被設為相應的錯誤型別。
如果 type 引數不合法,errno將返回EINVAL
istringstream的功能是網上查的,需要了解可以自行檢視