名稱空間
變體
操作

std::remove

來自 cppreference.com
< cpp‎ | io‎ | c
 
 
 
 
定義於標頭檔案 <cstdio>
int remove( const char* pathname );

刪除由 pathname 指向的字串標識的檔案。

如果檔案當前被任何程序開啟,此函式的行為是實現定義的。POSIX 系統取消檔名的連結(目錄條目),但檔案佔用的檔案系統空間在檔案被任何程序開啟且存在其他硬連結時不會被回收。Windows 在這種情況下不允許刪除檔案。

目錄

[編輯] 引數

pathname - 指向以 null 結尾的字串的指標,該字串包含標識要刪除的檔案的路徑

[編輯] 返回值

成功時返回 0,錯誤時返回非零值。

[編輯] 注意

POSIX 指定了此函式行為的許多額外細節。

標準庫還定義了一個函式模板 std::remove,它接受一對迭代器和一個值,此過載是標準演算法之一。

[編輯] 示例

#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
 
int main()
{
    // create a file, check success using operator! of temporary stream object
    if (!std::ofstream("file1.txt").put('a'))
    {
        std::perror("Error creating file1.txt");
        return EXIT_FAILURE;
    }
    std::cout << std::ifstream("file1.txt").rdbuf() << '\n'; // print file
 
    std::remove("file1.txt"); // delete file
 
    if (!std::ifstream{"file1.txt"}) // uses operator! of temporary stream object
    {
        std::perror("Error opening deleted file");
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

可能的輸出

a
Error opening deleted file: No such file or directory

[編輯] 參閱

(C++17)(C++17)
刪除檔案或空目錄
刪除檔案或目錄及其所有內容,遞迴進行
(function) [編輯]
重新命名檔案
(function) [編輯]
C 文件 關於 remove