我試圖編寫一個程序,執行上述工作,並找到以下工作。
您可以使用strtok()
從輸入中提取所有單個目錄,併爲每個子目錄應用 mkdir()
。最後/
後面的字符串是文件名和我不知道是否有更好的方法來解析字符串使用strtok()我的方式:我調用一個函數countChars()(從https://stackoverflow.com/a/4235545/1024474借來)到確定路徑中/
的數量以獲取要創建的文件夾數量,並相應地使用while
循環來創建目錄。
最後,我使用creat()創建一個具有指定路徑的文件名的文件。在你的代碼中,你可以將原始文件的內容複製到新文件中。
下面的代碼假定您已經在預定backup/
文件夾的路徑是一樣的東西users/username/documents/folder/file.txt
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int countChars(char* s, char c)
{
return *s == '\0'
? 0
: countChars(s + 1, c) + (*s == c);
}
int main(int argc, char **argv) {
mode_t mode = S_IRWXU;
umask(0);
char buffer[512];
char *b;
char c[512];
int n, i=0;
strcpy(buffer, argv[1]);
n = countChars(buffer, '/');
printf("%d\n", n);
b = strtok(buffer, "/");
while (i<n)
{
i++;
printf("%s\n", b);
if (mkdir(b, mode) == -1) {
printf("error when creating dir\n");
}
chdir(b);
b = strtok(NULL, "/");
}
if (creat(b, mode) == -1) {
printf("error when creating file\n");
}
return 0;
}
如果文件夾已經存在,程序打印一個錯誤(即通知),但收益。
您正在使用哪個操作系統? – Baldrick
這取決於您必須使用哪些系統調用來創建目錄。如果這是UNIX或Linux,則可以爲樹中的每個目錄調用mkdir()。從示例字符串中的任何目錄開始不存在。如果/ backup已經存在,請以/ backup/users開頭。 –
在Windows下,使用SHCreateDirectoryEx窗口函數。它一次性創建路徑的所有缺失部分。 – Baldrick