C++ Go語言實現(xiàn)將windows和linux文件刪除至回收站
C++
在C++中,將文件移動到回收站的實現(xiàn)在Linux和Windows平臺上是不同的。首先,我會為你提供在Windows平臺上實現(xiàn)的代碼示例,然后再提供Linux平臺上的對應實現(xiàn)。
Windows平臺
在Windows平臺上,你可以使用SHFileOperation函數(shù)來將文件移動到回收站。這個函數(shù)定義在Shellapi.h頭文件中。以下是一個簡單的示例
#include <windows.h> #include <shellapi.h> void moveToRecycleBin(const char* filePath) { SHFILEOPSTRUCT fileOp; ZeroMemory(&fileOp, sizeof(fileOp)); fileOp.wFunc = FO_DELETE; fileOp.pFrom = filePath; fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; SHFileOperation(&fileOp); } int main() { moveToRecycleBin("C:\\path\\to\\your\\file.txt"); return 0; }
Linux平臺
在Linux系統(tǒng)中,將文件“刪除”到回收站的操作實際上并不是直接刪除文件,而是將其移動到一個特定的目錄(通常是用戶目錄下的一個隱藏文件夾)。這是因為Linux沒有一個統(tǒng)一的、系統(tǒng)級的回收站功能,不像Windows的回收站那樣。因此,將文件“刪除”到回收站實際上是把文件從它原來的位置移動到這個隱藏的回收站目錄。
#include <iostream> #include <fstream> #include <string> #include <sys/stat.h> #include <unistd.h> bool moveToTrash(const std::string& filePath) { const char* homeDir = getenv("HOME"); if (!homeDir) { std::cerr << "Error: HOME environment variable not set." << std::endl; return false; } std::string trashFilesPath = std::string(homeDir) + "/.local/share/Trash/files/"; std::string trashInfoPath = std::string(homeDir) + "/.local/share/Trash/info/"; std::string baseName = filePath.substr(filePath.find_last_of('/') + 1); std::string destFilePath = trashFilesPath + baseName; std::string destInfoPath = trashInfoPath + baseName + ".trashinfo"; // 創(chuàng)建回收站文件和信息目錄(如果不存在) mkdir(trashFilesPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); mkdir(trashInfoPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); // 寫入.trashinfo文件 std::ofstream trashInfoFile(destInfoPath); if (!trashInfoFile) { std::cerr << "Error: Unable to create trash info file." << std::endl; return false; } trashInfoFile << "[Trash Info]\nPath=" << filePath << "\nDeletionDate=" << /* 獲取當前日期和時間的代碼 */ "\n"; trashInfoFile.close(); // 移動文件到回收站 if (rename(filePath.c_str(), destFilePath.c_str()) != 0) { perror("Error moving file to trash"); return false; } return true; } int main() { std::string filePath = "/path/to/your/file.txt"; // 替換為要刪除的文件路徑 if (!moveToTrash(filePath)) { return 1; } return 0; }
跨平臺,代碼合并
要在同一個程序中同時支持Windows和Linux平臺的文件刪除到回收站的功能,我們可以使用預處理器指令來區(qū)分操作系統(tǒng),并在每個平臺上執(zhí)行相應的操作。同時,為了確保代碼的穩(wěn)定性,我們需要添加適當?shù)腻e誤處理來避免程序崩潰即使在刪除失敗的情況下。以下是一個跨平臺的示例實現(xiàn)
#include <iostream> #include <string> #include <cstdlib> #include <cstdio> #ifdef _WIN32 #include <windows.h> #include <shellapi.h> #endif #ifdef __linux__ #include <sys/stat.h> #include <unistd.h> #endif bool moveToRecycleBin(const std::string& filePath) { #ifdef _WIN32 // Windows 實現(xiàn) SHFILEOPSTRUCT shfos; ZeroMemory(&shfos, sizeof(shfos)); shfos.wFunc = FO_DELETE; shfos.pFrom = filePath.c_str(); shfos.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; return SHFileOperation(&shfos) == 0; #elif __linux__ // Linux 實現(xiàn) const char* homeDir = getenv("HOME"); if (!homeDir) { std::cerr << "Error: HOME environment variable not set." << std::endl; return false; } std::string trashFilesPath = std::string(homeDir) + "/.local/share/Trash/files/"; std::string trashInfoPath = std::string(homeDir) + "/.local/share/Trash/info/"; std::string baseName = filePath.substr(filePath.find_last_of('/') + 1); std::string destFilePath = trashFilesPath + baseName; std::string destInfoPath = trashInfoPath + baseName + ".trashinfo"; mkdir(trashFilesPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); mkdir(trashInfoPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); std::ofstream trashInfoFile(destInfoPath); if (!trashInfoFile) { std::cerr << "Error: Unable to create trash info file." << std::endl; return false; } trashInfoFile << "[Trash Info]\nPath=" << filePath << "\nDeletionDate=" << /* 獲取當前日期和時間的代碼 */ "\n"; trashInfoFile.close(); return rename(filePath.c_str(), destFilePath.c_str()) == 0; #else std::cerr << "Unsupported platform." << std::endl; return false; #endif } int main() { std::string filePath = "/path/to/your/file.txt"; // 替換為要刪除的文件路徑 if (!moveToRecycleBin(filePath)) { std::cerr << "Failed to move file to recycle bin." << std::endl; return 1; } return 0; }
Go
在Go語言中,將文件移動到回收站的功能比較復雜,因為Go本身沒有提供直接操作系統(tǒng)回收站的API。這意味著你需要調用操作系統(tǒng)特定的功能。對于Windows,你可以使用系統(tǒng)調用來調用相應的Windows API。而在Linux上,由于標準的“回收站”是桌面環(huán)境特定的,通常的做法是將文件移動到一個特定的目錄(例如,基于FreeDesktop.org規(guī)范的“回收站”目錄)。
實現(xiàn)步驟
平臺檢測:首先,你需要檢測運行程序的平臺,以便確定使用哪種方法。
Windows實現(xiàn):在Windows上,你可以使用syscall包來調用SHFileOperation函數(shù),它是Windows API的一部分,用于執(zhí)行文件操作,包括刪除到回收站。
Linux實現(xiàn):在Linux上,你可以簡單地將文件移動到特定的回收站目錄(通常是~/.local/share/Trash/files/),但這不是標準化的,可能會根據不同的桌面環(huán)境有所變化。
Go語言實現(xiàn)示例
以下是一個簡化的Go語言實現(xiàn)示例。請注意,這個示例僅適用于演示目的,并不包括詳細的錯誤處理和復雜的操作系統(tǒng)交互。
package main import ( "fmt" "os" "path/filepath" "runtime" "syscall" "unsafe" ) // Windows API常量 const ( FO_DELETE = 0x0003 FOF_ALLOWUNDO = 0x0040 FOF_NOCONFIRMATION = 0x0010 ) type SHFILEOPSTRUCT struct { hwnd syscall.Handle wFunc uint32 pFrom *uint16 pTo *uint16 fFlags uint16 fAnyOps bool hNameMappings uintptr lpszProgressTitle *uint16 } func moveToRecycleBin(filePath string) error { switch runtime.GOOS { case "windows": // Windows實現(xiàn) shFileOp := &SHFILEOPSTRUCT{ wFunc: FO_DELETE, pFrom: syscall.StringToUTF16Ptr(filePath + "\x00"), fFlags: FOF_ALLOWUNDO | FOF_NOCONFIRMATION, } shfileopProc, err := syscall.LoadDLL("shell32.dll").FindProc("SHFileOperationW") if err != nil { return err } ret, _, _ := shfileopProc.Call(uintptr(unsafe.Pointer(shFileOp))) if ret != 0 { return fmt.Errorf("SHFileOperationW failed: return value %d", ret) } case "linux": // Linux實現(xiàn) homeDir, err := os.UserHomeDir() if err != nil { return err } trashPath := filepath.Join(homeDir, ".local/share/Trash/files") if _, err := os.Stat(trashPath); os.IsNotExist(err) { if err := os.MkdirAll(trashPath, 0755); err != nil { return err } } baseName := filepath.Base(filePath) destPath := filepath.Join(trashPath, baseName) err = os.Rename(filePath, destPath) if err != nil { return err } default: return fmt.Errorf("unsupported platform") } return nil } func main() { err := moveToRecycleBin("C:\\path\\to\\your\\file.txt") // 替換為你要刪除的文件路徑 if err != nil { fmt.Println("Error:", err) os.Exit(1) } }
平臺檢測:通過runtime.GOOS檢測運行的操作系統(tǒng)。
Windows實現(xiàn):(注釋掉的部分)需要使用syscall包來調用Windows API。這是一個比較高級和復雜的操作,需要對Windows API有深入了解。
Linux實現(xiàn):簡單地將文件移動到預定義的回收站目錄。
錯誤處理:在實際應用中,應該添加更多的錯誤處理邏輯以處理各種可能的異常情況。
go單獨的windows版本實現(xiàn)
在Go語言中實現(xiàn)將文件移動到Windows回收站的功能相對復雜,因為需要使用Windows API。這通常涉及到調用SHFileOperation函數(shù)。在Go中,你可以通過syscall包來進行系統(tǒng)調用。以下是一個可能的實現(xiàn)方式,但請注意,這需要對Windows API有一定的了解,并且可能需要根據你的具體需求進行調整。
package main import ( "fmt" "os" "syscall" "unsafe" ) const ( FO_DELETE = 0x0003 FOF_ALLOWUNDO = 0x0040 FOF_NOCONFIRMATION = 0x0010 ) type SHFILEOPSTRUCT struct { hwnd syscall.Handle wFunc uint32 pFrom *uint16 pTo *uint16 fFlags uint16 fAnyOps bool hNameMappings uintptr lpszProgressTitle *uint16 } func moveToRecycleBin(filePath string) error { shFileOp := &SHFILEOPSTRUCT{ wFunc: FO_DELETE, pFrom: syscall.StringToUTF16Ptr(filePath + "\x00"), fFlags: FOF_ALLOWUNDO | FOF_NOCONFIRMATION, } shfileopProc, err := syscall.LoadDLL("shell32.dll").FindProc("SHFileOperationW") if err != nil { return err } ret, _, _ := shfileopProc.Call(uintptr(unsafe.Pointer(shFileOp))) if ret != 0 { return fmt.Errorf("SHFileOperationW failed: return value %d", ret) } return nil } func main() { err := moveToRecycleBin("C:\\path\\to\\your\\file.txt") // 替換為要刪除的文件路徑 if err != nil { fmt.Println("Error:", err) os.Exit(1) } }
代碼解釋
1.常量定義:定義了一些需要用到的常量,比如FO_DELETE(用于刪除操作)和FOF_ALLOWUNDO(允許撤銷)。
2.SHFILEOPSTRUCT結構體:這個結構體用于SHFileOperation函數(shù)的參數(shù),包含了操作類型、源文件路徑、目標文件路徑(在這個例子中不使用),以及其他標志。
3.moveToRecycleBin函數(shù):
- 將文件路徑轉換為以空字符結尾的UTF-16字符串。
- 加載shell32.dll動態(tài)鏈接庫并查找SHFileOperationW函數(shù)。
- 調用SHFileOperationW函數(shù)來執(zhí)行刪除操作。如果返回值不為0,則表示操作失敗。
4.錯誤處理:如果加載DLL或查找函數(shù)失敗,或者函數(shù)執(zhí)行返回錯誤,函數(shù)會返回相應的錯誤。
以上就是C++ Go語言實現(xiàn)將windows和linux文件刪除至回收站的詳細內容,更多關于C++ Go文件刪除至回收站的資料請關注腳本之家其它相關文章!
相關文章
MacOS上Homebrew?安裝、配置、更改國內鏡像源及使用圖文詳解
Homebrew是一個強大的包管理器,適用于macOS和Linux系統(tǒng),可以簡化軟件的安裝、升級和卸載過程,它包括brew、homebrew-core、homebrew-cask和homebrew-bottles四個主要部分,通過tap和cask可以擴展功能,安裝圖形界面應用,Homebrew還提供了各種命令來管理和維護已安裝的軟件包2024-11-11超實用Internet Download Manager(IDM)破解注冊碼,全版本通用
IDM下載器是一個十分好用的文件下載工具。IDM下載器它能夠幫助你提升5倍的下載速度,強大的續(xù)傳功能,讓你不再擔心因網絡問題、計算機宕機、停電等原因所造成的數(shù)據不全問題,下面小編給大家?guī)砹薎nternet Download Manager(IDM)破解注冊碼,感興趣的朋友參考下吧2023-01-01