我正在嘗試逐個字符地遍歷一個字符陣列并將其復制到另一個字符陣列中,直到讀取的字符為 \ 因為我想創建地址的目錄(如果未創建)或訪問(如果已創建)。
例如:
Adress: dir2/dir3/a
我的演算法:
path = dir2
//if dir2 not created make dir2 and change actual directory to dir2
//if created then access dir2 changing the actual directory to dir2
//empty path with memset and keep storing the adress
path = dir3
//repeat...
但是當我嘗試訪問路徑時,我得到了最后一個字符,而不是所有的路徑字串
輸出:
path0: d
path1: i //Should be di
path2: r //Should be dir
path3: 2 //Should be dir2
path: 2 //Should be dir2
我不知道是否有更有效的方法來執行此操作,并且我不知道如何獲取完整的路徑字串而不是最后一個字符,我在末尾插入了 '\0' 以防萬一字串結束字符的問題
name 和 path 是一個 char[256] 變數
代碼:
for (i = 0; i < strlen(name); i )
{
if(name[i] != '/')
{
path[j] = name[i];
path[i 1] = '\0';
printf("path%d: %s\n", i,path);
}
else
{
path[i] = '\0';
printf("path: %s\n", path);
n = chdir(path);
if(n == ENOENT)
{
n = mkdir(path, 0777);
if (n != 0)
{
fprintf(stderr, "Failed to make the directory to extract: %s\n", strerror(errno));
close(fmypack);
return E_DIR1;
}
chdir(path);
}
else if(n == EACCES)
{
fprintf(stderr, "Failed to access the directory: %s, %s\n", path, strerror(errno));
close(fmypack);
return E_DIR2;
}
else if(n != 0)
{
fprintf(stderr, "Unknow error when try to access the directory: %s, %s\n", path, strerror(errno));
close(fmypack);
return E_DESCO;
}
memset(path, 0, sizeof path);
j=0;
}
uj5u.com熱心網友回復:
我想我找到了。
path[i] = '\0';
但是路徑是使用j索引器建立的。
path[j] = '\0';
應該是正確的。
你錯過了你的增量j:
path[j] = name[i];
path[i 1] = '\0';
應該:
path[j ] = name[i];
path[j 1] = '\0';
有趣的是,使用 一次執行一個組件實際上更快,chdir()但是您發現它的可能性很小。當你得到幾百個目錄時,你可以測量它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452548.html
上一篇:了解信號阻塞和信號暫停
