请问unix高级编程中文件I/O包含哪些部分,附上例子和详细解释的注释
时间: 2023-02-28 13:59:15 浏览: 74
在 Unix 高级编程中,文件 I/O 包括以下几个部分:
1. 文件打开与关闭:使用 `open()` 函数打开文件,使用 `close()` 函数关闭文件。
例如:
```
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd;
/* 以读写方式打开文件 */
fd = open("file.txt", O_RDWR);
if (fd == -1) {
/* 打开文件失败 */
}
/* 关闭文件 */
close(fd);
return 0;
}
```
2. 文件读取:使用 `read()` 函数读取文件内容。
例如:
```
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd;
char buffer[1024];
int n;
/* 以读写方式打开文件 */
fd = open("file.txt", O_RDONLY);
if (fd == -1) {
/* 打开文件失败 */
}
/* 读取文件内容 */
n = read(fd, buffer, sizeof(buffer));
if (n == -1) {
/* 读取文件失败 */
}
/* 关闭文件 */
close(fd);
return 0;
}
```
3. 文件写入:使用 `write()` 函数写入文件内容。
例如:
```
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd;
char buffer[] = "Hello, world!";
int n;
/* 以读写方式打开文件 */
fd = open("file.txt", O_WRONLY);
if (fd == -1) {
/* 打开文件失败 */
}
/* 写入文件内容 */
n = write(fd, buffer, sizeof(buffer));
if (n == -1) {
/*