在Linux系統中,C++可以通過系統調用(syscall)與操作系統內核進行交互。系統調用是一組預定義的函數,允許用戶空間的程序請求內核執行特權操作,如文件操作、進程控制、通信等。以下是一些常用的Linux系統調用接口及其相關功能:
以下是一個簡單的示例,演示如何使用open()
和read()
系統調用讀取文件內容:
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
std::cerr << "Failed to open file" << std::endl;
return 1;
}
char buffer[1024];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead == -1) {
std::cerr << "Failed to read file" << std::endl;
close(fd);
return 1;
}
buffer[bytesRead] = '\0'; // Null-terminate the string
std::cout << buffer << std::endl;
close(fd);
return 0;
}
這個示例展示了如何打開一個文件,讀取其內容,并將其打印到標準輸出。希望這些信息對你有所幫助!