fork(2) download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstring>
  4. #include <string>
  5.  
  6. void getFileName(const std::string& path, std::string& fileName) {
  7. int pos = (int)path.size() - 1;
  8. for (; pos >= 0; --pos) {
  9. if (path[pos] == '/') {
  10. break;
  11. }
  12. }
  13. fileName = path.substr(pos+1);
  14. }
  15.  
  16. void formatDirPath(std::string& dirPath) {
  17. if (!dirPath.empty() || dirPath.back() != '/') {
  18. dirPath += '/';
  19. }
  20. }
  21.  
  22. int getFileSize(std::ifstream& fin) {
  23. fin.seekg(0, fin.end);
  24. int fileSize = fin.tellg();
  25. fin.seekg(0);
  26. return fileSize;
  27. }
  28.  
  29. void readBinFile(const std::string& path, int& bufferSize, char*& buffer) {
  30. std::ifstream fin(path, std::ios::binary);
  31. if (!fin.is_open()) {
  32. std::cout << "Cannot open " << path << '\n';
  33. return;
  34. }
  35. bufferSize = getFileSize(fin);
  36. buffer = new char[bufferSize];
  37. fin.read(buffer, bufferSize);
  38. fin.close();
  39. }
  40.  
  41. void writeBinFile(const std::string& path, int bufferSize, char* buffer) {
  42. std::ofstream fout(path, std::ios::binary);
  43. if (!fout.is_open()) {
  44. std::cout << "Cannot open " << path << '\n';
  45. return;
  46. }
  47. fout.write(buffer, bufferSize);
  48. fout.close();
  49. }
  50.  
  51. int main(int argc, char** argv) {
  52. std::string filePath;
  53. std::string outDir;
  54.  
  55. if (argc != 5) {
  56. std::cout << "Invalid arguments\n";
  57. return 0;
  58. } else {
  59. for (int i = 1; i < 5; i+=2) {
  60. if (strcmp(argv[i], "-s") == 0) {
  61. filePath = argv[i+1];
  62. } else if (strcmp(argv[i], "-d") == 0) {
  63. outDir = argv[i+1];
  64. }
  65. }
  66. if (filePath.empty()) {
  67. std::cout << "Source file not found in arguments!\n";
  68. return 0;
  69. } else if (outDir.empty()) {
  70. std::cout << "Destination not found in arguments!\n";
  71. return 0;
  72. }
  73. }
  74.  
  75.  
  76. std::string fileName;
  77. getFileName(filePath, fileName);
  78.  
  79. formatDirPath(outDir);
  80. std::string outPath = outDir + fileName;
  81.  
  82. int bufferSize;
  83. char* buffer = nullptr;
  84. readBinFile(filePath, bufferSize, buffer);
  85.  
  86. writeBinFile(outPath, bufferSize, buffer);
  87.  
  88. delete[] buffer;
  89.  
  90. return 0;
  91. }
Success #stdin #stdout 0.01s 5548KB
stdin
Standard input is empty
stdout
Invalid arguments