58 lines
1.9 KiB
C
58 lines
1.9 KiB
C
/*
|
||
Program: recursive-check-path.c
|
||
Function: 以間接遞迴的方式檢視字串是否代表有效的目錄夾路徑。有效的路徑為斜線及若干英數字元組成的
|
||
字串,本程式設isValidPath()專責檢視非英數字元(斜線)的部分,剩餘的英數字元串交由checkPathChar()
|
||
處理,而checkPathChar()運行過程中若發現斜線字元,將呼叫isValidPath(),透過這二個函式互相呼叫,達到
|
||
檢視的效果
|
||
Note: 本程式係由ChatGPT產生第一版的應用例,紀老師再加以擴充改寫,希助同學掌握間接遞迴的精隨
|
||
*/
|
||
|
||
#include <stdio.h>
|
||
#include <string.h>
|
||
|
||
int isValidPath(char *path);
|
||
int checkPathChar(char *path);
|
||
|
||
int isValidPath(char *path) {
|
||
if (path[0] == '\0')
|
||
return 0; //回傳0,代表path為"無效"路徑
|
||
else if (path[0] == '/')
|
||
return checkPathChar(path+1); //接著檢視path+1代表的字串是否為有效路徑
|
||
else if (isalnum(path[0]))
|
||
return checkPathChar(path); //呼叫checkPathChar()檢視path代表的字串是否為有效路徑
|
||
else
|
||
return 0; //回傳0,代表path為"無效"路徑
|
||
}
|
||
|
||
int checkPathChar(char *path) {
|
||
if (path[0] == '\0')
|
||
return 1; //回傳1,代表path為"有效"路徑
|
||
else if (isalnum(path[0])) //當下path首為英數字元,則繼續呼叫checkPathChar檢視接下來的字元串是否符合
|
||
return checkPathChar(path+1);
|
||
else if ((path[0] == '/') && (path[1] != '/')) //不能連續出現"//"
|
||
return isValidPath(path+1);
|
||
else
|
||
return 0; //回傳0,代表path為"無效"路徑
|
||
}
|
||
|
||
int main() {
|
||
char *paths[] = {
|
||
"/home/user/docs", //有效
|
||
"/home/user//docs", //無效(含有連續二個正斜線'/'符號)
|
||
"/home/user/abc!", //無效(包含非英數字元)
|
||
"/documents", //有效
|
||
"!valid/start", //無效
|
||
"/home/1234" //有效
|
||
};
|
||
|
||
int i, count = sizeof(paths)/sizeof(paths[0]);
|
||
|
||
for (i = 0; i < count; i++)
|
||
if (isValidPath(paths[i]))
|
||
printf("\"%s\" 為有效路徑 O\n",paths[i]);
|
||
else
|
||
printf("\"%s\" 非有效路徑 X\n",paths[i]);
|
||
|
||
return 0;
|
||
}
|