Ghytro

Untitled

Sep 17th, 2021
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4.  
  5. enum file_extension
  6. {
  7. C,
  8. PY,
  9. JS,
  10. UNDEFINED
  11. };
  12.  
  13. bool string_ends_with(const std::string& str, const std::string& ending)
  14. {
  15. return !str.compare(str.size() - ending.size(), str.size(), ending) && str.length() >= ending.length();
  16. }
  17.  
  18. file_extension get_file_extension(const std::string& filename)
  19. {
  20. if (string_ends_with(filename, ".py"))
  21. return PY;
  22. if (string_ends_with(filename, ".js"))
  23. return JS;
  24. if (string_ends_with(filename, ".c"))
  25. return C;
  26. return UNDEFINED;
  27. }
  28.  
  29. void search_comments(const std::string& filename)
  30. {
  31. std::vector<std::string> comment_tokens;
  32. switch (get_file_extension(filename))
  33. {
  34. case PY:
  35. comment_tokens = {"#", "\"\"\""};
  36. break;
  37.  
  38. case C:
  39. case JS:
  40. comment_tokens = {"//", "/*"};
  41. break;
  42.  
  43. default:
  44. std::cout << "Incorrect file extension. Allowed file extensions are: .c, .js, .py" << std::endl;
  45. return;
  46. }
  47. std::ifstream fin(filename);
  48. if (!fin.is_open())
  49. {
  50. std::cout << "Unable to open file, check if it exists" << std::endl;
  51. return;
  52. }
  53. fin.close();
  54.  
  55. std::string line;
  56. while (std::getline(fin, line))
  57. {
  58. for (const auto& token: comment_tokens)
  59. {
  60. if (line.find(token) != std::string::npos)
  61. {
  62. std::cout << "File contains comments" << std::endl;
  63. return;
  64. }
  65. }
  66. }
  67. std::cout << "File does not contain comments" << std::endl;
  68. }
  69.  
  70. int main(int argc, const char* argv[])
  71. {
  72. if (argc < 1)
  73. {
  74. std::cout << "Specify the file to check comments" << std::endl;
  75. return 0;
  76. }
  77. std::cout << argv[0] << std::endl;
  78. search_comments(argv[0]);
  79. return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment