file.c 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * 文件名: file.c
  3. * 目标: 关于文件读取的实用函数
  4. */
  5. #include <sys/stat.h>
  6. #include <string.h>
  7. #include <ctype.h>
  8. #include <assert.h>
  9. #include "tool.h"
  10. #include "mem.h"
  11. #ifndef S_ISREG
  12. #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  13. #endif
  14. #ifndef S_ISDIR
  15. #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
  16. #endif
  17. /*
  18. * 函数名: checkFile
  19. * 目标判断文件类型, 若是普通文件返回1, 若是文件夹返回2, 其他遇到错误返回0
  20. */
  21. int checkFile(char *path){
  22. struct stat my_stat;
  23. if (path == NULL || stat(path, &my_stat) != 0)
  24. return 0;
  25. if (S_ISREG(my_stat.st_mode)) // 普通文件
  26. return 1;
  27. else if (S_ISDIR(my_stat.st_mode))
  28. return 2;
  29. else
  30. return 0;
  31. }
  32. /*
  33. * 函数: getFileName
  34. * 目标: 给定路径获取该路径所指定的文件名
  35. */
  36. char *getFileName(char *path_1){
  37. char *slash = NULL; // 名字开始的字符的指针
  38. char *point = NULL; // 后缀名.所在的字符的指针
  39. char *name = NULL; // 返回值
  40. char *path = strCopy(path_1); // 复制数组, 避免path_1是常量字符串导致无法修改其值
  41. if (path[STR_LEN(path) - 1] == SEP_CH) // 若路径的最后一个字符为SEP, 则忽略此SEP
  42. path[STR_LEN(path) - 1] = NUL;
  43. if ((slash = strrchr(path, SEP_CH)) == NULL)
  44. slash = path;
  45. else
  46. slash++;
  47. if ((point = strchr(path, '.')) != NULL)
  48. *point = NUL;
  49. name = strCopy(slash);
  50. safeFree_(path);
  51. if (!isalpha(*name) && *name != '_')
  52. name = strJoin("_", name, false, true);
  53. for (char *tmp = name; *tmp != 0; tmp++)
  54. if (!isalnum(*tmp) &&'_' != *tmp)
  55. *tmp = '_';
  56. return name;
  57. }
  58. /*
  59. * 函数名: fileNameToVar
  60. * 目标: 把一个文件名转换为合法的变量名(替换不合法字符为_)
  61. */
  62. char *fileNameToVar(char *name, bool need_free){
  63. char *var;
  64. if (need_free)
  65. var = name; // 在原数据上修改
  66. else
  67. var = strCopy(name); // 复制新的数据再修改
  68. if (!isalpha(*var) && *var != '_')
  69. var = strJoin("_", var, false, true);
  70. for (char *tmp = var; *tmp != 0; tmp++)
  71. if (!isalnum(*tmp) &&'_' != *tmp)
  72. *tmp = '_';
  73. return var;
  74. }
  75. /*
  76. * 函数名: findPath
  77. * 目标: 转换路径为合法路径(相对路径->绝对路径, 绝对路径保持不变)
  78. */
  79. #include "stdio.h"
  80. char *findPath(char *path, char *env, bool need_free){
  81. assert(env[STR_LEN(env) - 1] == SEP_CH); // env 必须以 SEP 结尾
  82. #ifdef __linux
  83. if (path[0] != SEP_CH) { // 不以 / 开头
  84. #else
  85. if (!(isupper(path[0]) && (path)[1] == ':')) { // 不以盘符开头
  86. #endif
  87. return strJoin(env, path, false, need_free); // 调整为相对路径模式
  88. } else if (!need_free) { // 若设置了need_free为true, 则等于先复制在释放原来的, 等于没有复制, 所以不做操作
  89. return strCopy(path);
  90. } else {
  91. return path;
  92. }
  93. }