char *program_working_dir;
char backup_dir[9]="/Backups/";
// getting the current working directory
program_working_dir = getcwd(NULL, 0);
if (program_working_dir == NULL){
printf("Failed to get working directory( take_backup function )\n");
return -1;
}
// allocate memory for full path that contain the current directory and the /Backups/
char *full_backup_dir = (char *)malloc( (strlen(program_working_dir) + strlen(backup_dir) + 1 ) * sizeof(uint8_t) );
if (full_backup_dir == NULL){
printf("Failed to allocate proper memory to stor full path of backup directory\n");
return -1;
}
// used for debugging purposes
printf("program working dir%s\n", program_working_dir); // (here : /home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing/)
printf("%d\n", strlen(program_working_dir)); // ( 86 length of program_working_dir )
// try to concatenate the tow string using snprintf. I add 1 to size for '\0' terminate string
snprintf(full_backup_dir, ( strlen(program_working_dir) + strlen(backup_dir) +1 ) * sizeof(uint8_t) , "%s%s", program_working_dir, backup_dir);
printf("Full path: %s\n", full_backup_dir);
在这里,我只是尝试将两个字符串(路径)连接在一起,但有时我执行它时它不能正常工作。例如我得到这个:
program working dir/home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing
86
path /home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing/Backups/��M�X
正如您在连接后看到的那样,我得到了有线字符串 /��M�X,这破坏了我的所有程序,我不明白为什么会发生这种情况。我也尝试使用 strncpy 和 strncat 做同样的事情,所以我替换了以下行:
snprintf(full_backup_dir, ( strlen(program_working_dir) + strlen(backup_dir) +1 ) * sizeof(char) , "%s%s", program_working_dir, backup_dir);
至
strcpy(full_backup_dir, program_working_dir);
strcat(full_backup_dir, backup_dir);
仍然有同样的问题。我还删除了我添加到 full_back_dir 大小的 1,但是这个程序又不想正常运行。在这一点上,我真的很感激任何帮助和反馈。请帮忙!!!!