How can I create files inside dynamically created directories?

时间:2015-06-25 19:11:06

标签: c linux

I need to copy files inside dynamically created directory. This is the code: FILE *fp, *source, *target; int i, j, k, counter; char str[256], str1[256]; char ch; const char *a[5]; a[1] = "submit.sh"; a[2] = "run.prm"; a[3] = "name.txt"; a[4] = "prot.pdb"; for (i=1; i<=4; i++) { sprintf(str,"%s_%d",cur_folder, i); mkdir(str,"w"); for (j=1;j<3;j++) { sprintf(str,"%s%s",cur_folder, a[j]); source = fopen(str, "r"); if( source == NULL ) { printf("Error in energies_step, can't open file source \n"); return USERERR; } sprintf(str,"/home/salah/proteins/1L2Y/try5_4changes/_%d/%s",i,a[j]); target = fopen(str, "w"); if( target == NULL ) { fclose(source); printf("Error in energies_step, can't open file target %s \n",str); return USERERR; } while( ( ch = fgetc(source) ) != EOF ) fputc(ch, target); } } This code breaks and tell me that target is NULL. Why can't I create new file inside the directory?

1 个答案:

答案 0 :(得分:1)

正如@MarkPlotnick在评论中提到的,这一行不正确:

mkdir(str, "w");

但不是为文件权限编写显式数字,例如:

mkdir(str, 0755);

你应该更好地使用相应的符号常量,例如:

mkdir(str, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);

可以找到更好地使用符号常量的原因here

  

警告:编写文件权限的显式数字是不好的做法。它不仅不便携,而且还要求每个阅读程序的人都记住这些位的含义。要使程序清洁,请使用符号名称。

符号常量在头文件 sys / stat.h 中定义。