在Ubuntu系統中使用C++進行文件操作,你可以使用C++標準庫中的<fstream>頭文件提供的類和函數。以下是一些基本的文件操作示例:
包含頭文件:
#include <iostream>
#include <fstream>
#include <string>
寫入文件:
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();
}
讀取文件:
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();
}
追加內容到文件:
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();
}
檢查文件是否存在:
bool fileExists(const std::string& filename) {
std::ifstream inFile(filename);
return inFile.good();
}
刪除文件:
void deleteFile(const std::string& filename) {
if (std::remove(filename.c_str()) != 0) {
std::cerr << "Error deleting the file!" << std::endl;
}
}
重命名文件:
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;
}
}
獲取文件大小:
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
確保你有足夠的權限來執行這些操作,否則可能會遇到權限錯誤。