溫馨提示×

ubuntu c++文件操作怎樣做

小樊
72
2025-06-14 00:04:24
欄目: 編程語言

在Ubuntu系統中使用C++進行文件操作,你可以使用C++標準庫中的<fstream>頭文件提供的類和函數。以下是一些基本的文件操作示例:

  1. 包含頭文件

    #include <iostream>
    #include <fstream>
    #include <string>
    
  2. 寫入文件

    void writeFile(const std::string& filename) {
        std::ofstream outFile(filename);
        if (!outFile.is_open()) {
            std::cerr << "Error opening file for writing!" << std::endl;
            return;
        }
        outFile << "Hello, World!" << std::endl;
        outFile.close();
    }
    
  3. 讀取文件

    void readFile(const std::string& filename) {
        std::ifstream inFile(filename);
        if (!inFile.is_open()) {
            std::cerr << "Error opening file for reading!" << std::endl;
            return;
        }
        std::string line;
        while (std::getline(inFile, line)) {
            std::cout << line << std::endl;
        }
        inFile.close();
    }
    
  4. 追加內容到文件

    void appendToFile(const std::string& filename) {
        std::ofstream outFile(filename, std::ios::app);
        if (!outFile.is_open()) {
            std::cerr << "Error opening file for appending!" << std::endl;
            return;
        }
        outFile << "Appended text" << std::endl;
        outFile.close();
    }
    
  5. 檢查文件是否存在

    bool fileExists(const std::string& filename) {
        std::ifstream inFile(filename);
        return inFile.good();
    }
    
  6. 刪除文件

    void deleteFile(const std::string& filename) {
        if (std::remove(filename.c_str()) != 0) {
            std::cerr << "Error deleting the file!" << std::endl;
        }
    }
    
  7. 重命名文件

    void renameFile(const std::string& oldName, const std::string& newName) {
        if (std::rename(oldName.c_str(), newName.c_str()) != 0) {
            std::cerr << "Error renaming the file!" << std::endl;
        }
    }
    
  8. 獲取文件大小

    std::streamsize getFileSize(const std::string& filename) {
        std::ifstream inFile(filename, std::ios::binary | std::ios::ate);
        if (!inFile.is_open()) {
            std::cerr << "Error opening file to get size!" << std::endl;
            return -1;
        }
        return inFile.tellg();
    }
    

使用這些基本的文件操作函數,你可以在Ubuntu系統上使用C++進行文件的讀寫、追加、刪除、重命名等操作。記得在編譯C++程序時鏈接標準庫,通常使用g++編譯器:

g++ -o myprogram myprogram.cpp

然后運行生成的可執行文件:

./myprogram

確保你有足夠的權限來執行這些操作,否則可能會遇到權限錯誤。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女