在Linux中,C++可以通過多種方式來操作文件系統。以下是一些常用的方法:
#include <iostream>
#include <fstream>
int main() {
// 打開文件
std::ifstream infile("example.txt");
std::ofstream outfile("output.txt");
// 檢查文件是否成功打開
if (!infile.is_open() || !outfile.is_open()) {
std::cerr << "Error opening files!" << std::endl;
return 1;
}
// 寫入數據到文件
outfile << "Hello, World!" << std::endl;
// 從文件讀取數據
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
// 關閉文件
infile.close();
outfile.close();
return 0;
}
fopen()
, fclose()
, fread()
, fwrite()
, fseek()
等。#include <cstdio>
#include <cstring>
int main() {
FILE *infile = fopen("example.txt", "r");
FILE *outfile = fopen("output.txt", "w");
if (!infile || !outfile) {
perror("Error opening files");
return 1;
}
char buffer[256];
while (fgets(buffer, sizeof(buffer), infile)) {
fputs(buffer, outfile);
}
fclose(infile);
fclose(outfile);
return 0;
}
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
int main() {
int infile = open("example.txt", O_RDONLY);
if (infile == -1) {
perror("Error opening file");
return 1;
}
int outfile = open("output.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (outfile == -1) {
perror("Error creating output file");
close(infile);
return 1;
}
char buffer[256];
ssize_t bytes_read;
while ((bytes_read = read(infile, buffer, sizeof(buffer))) > 0) {
write(outfile, buffer, bytes_read);
}
close(infile);
close(outfile);
return 0;
}
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
// 創建目錄
fs::create_directory("new_directory");
// 復制文件
fs::copy_file("example.txt", "example_backup.txt");
// 刪除文件
fs::remove("example_backup.txt");
// 遍歷目錄
for (const auto& entry : fs::directory_iterator(".")) {
std::cout << entry.path() << std::endl;
}
return 0;
}
在使用這些方法時,需要注意錯誤處理和資源管理,確保文件在使用后被正確關閉,避免資源泄露。此外,當使用POSIX API或者C++17的文件系統庫時,需要確保編譯器支持相應的特性,并且在編譯時啟用相應的標準或庫。例如,使用C++17的文件系統庫時,可能需要添加編譯選項-std=c++17
。