Linux文件I/O的基础知识和使用方法,并提供相关的代码示例。
1. 文件I/O 基础
文件I/O指的是读写文件的操作,包括打开文件、读取数据、写入数据、关闭文件等操作。在Linux中,所有的I/O操作都是通过文件描述符(file descriptor)进行的。文件描述符是一个非负整数,由内核管理,每个进程都有一张文件描述表,记录了所有已打开的文件。
下面是一个简单的代码示例,演示如何打开文件、读取文件内容和关闭文件。代码中,open()函数用于打开文件,“r”参数表示以只读方式打开文件;read()函数用于读取文件内容,将内容保存在buffer数组中;close()函数则用于关闭文件。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd;
char buffer[1024];
// 打开文件
fd = open("test.txt", O_RDONLY);
if (fd == -1) {
printf("Error opening file");
exit(EXIT_FAILURE);
}
// 读取文件内容
if (read(fd, buffer, sizeof(buffer)) == -1) {
printf("Error reading file");
exit(EXIT_FAILURE);
}
// 输出文件内容
printf("File content:\n%s\n", buffer);
// 关闭文件
if (close(fd) == -1) {
printf("Error closing file");
exit(EXIT_FAILURE);
}
return 0;
}
2. 文件打开模式
在Linux中,打开文件时需要指定文件的打开模式。常用的文件打开模式有以下几种:
- O_RDONLY: 只读打开文件。
- O_WRONLY: 只写打开文件。
- O_RDWR: 读写打开文件。
- O_APPEND: 每次写操作都追加到文件末尾。
- O_CREAT: 文件不存在时创建文件。
下面是一个示例代码,演示如何使用不同的文件打开模式打开文件。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd;
// 只读模式打开文件
fd = open("read.txt", O_RDONLY);
if (fd == -1) {
printf("Error opening file");
exit(EXIT_FAILURE);
}
printf("Read-only mode: %d\n", fd);
close(fd);
// 只写模式打开文件
fd = open("write.txt", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
if (fd == -1) {
printf("Error opening file");
exit(EXIT_FAILURE);
}
printf("Write-only mode: %d\n", fd);
close(fd);
// 读写模式打开文件
fd = open("rw.txt", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
if (fd == -1) {
printf("Error opening file");
exit(EXIT_FAILURE);
}
printf("Read-write mode: %d\n", fd);
close(fd);
return 0;
}
3. 文件读写操作
在Linux中,文件读写操作可以使用read()和write()函数实现。read()函数用于从文件中读取数据,write()函数用于向文件中写入数据。这两个函数的参数很相似,都包括文件描述符、缓冲区指针和缓冲区大小。
下面是一个示例代码,演示如何使用read()和write()函数进行文件读写操作。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd;
char buffer[1024];
ssize_t ret;
// 打开文件
fd = open("test.txt", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
if (fd == -1) {
printf("Error opening file");
exit(EXIT_FAILURE);
}
// 写入文件内容
write(fd, "Hello World!", 12);
// 移动文件指针到文件开头
lseek(fd, 0, SEEK_SET);
// 读取文件内容
ret = read(fd, buffer, sizeof(buffer));
if (ret == -1) {
printf("Error reading file");
exit(EXIT_FAILURE);
}
// 输出文件内容
printf("File content:\n%.*s\n", (int)ret, buffer);
// 关闭文件
close(fd);
return 0;
}
4. 文件操作API
除了read()和write()函数之外,Linux还提供了其他一些与文件操作相关的API,例如:
-
open(): 打开文件。
-
close(): 关闭文件。
-
lseek(): 移动文件指针。
-
fcntl(): 对文件描述符进行控制操作。
-
dup(): 复制现有文件描述符。
这些API在文件操作中起着重要的作用,需要熟练掌握并使用。