util.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <dirent.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <limits.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <sys/time.h>
  10. #ifndef UTIL_H
  11. #define UTIL_H
  12. int get_user_count() {
  13. char* root = getenv("RELAT_ROOT");
  14. int count = 0;
  15. DIR* dirp;
  16. struct dirent* entry;
  17. if ((dirp = opendir(root)) == NULL) {
  18. perror("could not open root dir");
  19. exit(-1);
  20. }
  21. while ((entry = readdir(dirp)) != NULL) {
  22. char entry_path[256];
  23. sprintf(entry_path, "%s/%s", root, entry->d_name);
  24. struct stat* entry_stat;
  25. if (stat(entry_path, entry_stat) != 0) {
  26. perror("Could not read stats from entry");
  27. exit(-1);
  28. }
  29. if (!S_ISDIR(entry_stat->st_mode)) {
  30. continue;
  31. }
  32. // TODO: better check whether directory is really a user
  33. if (entry->d_namlen < 3) {
  34. continue;
  35. }
  36. count++;
  37. }
  38. return count;
  39. }
  40. unsigned long get_unix_timestamp() {
  41. struct timeval tv;
  42. gettimeofday(&tv, NULL);
  43. return (unsigned long)(tv.tv_sec) * 1000 + (unsigned long)(tv.tv_usec) / 1000;
  44. }
  45. void create_unit(char* user, char* unit, float x, float y) {
  46. char* root = getenv("RELAT_ROOT");
  47. char unit_directory[256];
  48. sprintf(unit_directory, "%s/%s/%s", root, user, unit);
  49. if (mkdir(unit_directory) != 0) {
  50. perror("mkdir failed");
  51. exit(-1);
  52. }
  53. char unit_pos_file_name[256];
  54. sprintf(unit_pos_file_name, "%s/%s/%s/position", root, user, unit);
  55. FILE* unit_pos_file;
  56. if ((unit_pos_file = fopen(unit_pos_file_name, "w")) == NULL) {
  57. perror("could not create position file for unit");
  58. exit(-1);
  59. }
  60. fprintf(unit_pos_file, "%.3f %.3f %.3f\n", x, y, 0.0f);
  61. fclose(unit_pos_file);
  62. char unit_move_file_name[256];
  63. sprintf(unit_move_file_name, "%s/%s/%s/move", root, user, unit);
  64. FILE* unit_move_file;
  65. if ((unit_move_file = fopen(unit_move_file_name, "w")) == NULL) {
  66. perror("could not create move file for unit");
  67. exit(-1);
  68. }
  69. fprintf(unit_move_file, "%ul %ul %.3f %.3f %.3f", 0l, ULONG_MAX, 0.0f, 0.0f, 0.0f);
  70. }
  71. #endif