Linux文件编程详解
在Ubuntu(Linux)系统下进行文件操作涉及一系列的系统调用,这些调用是基于Unix风格的文件操作API。这些操作包括打开或创建文件、从文件中读取数据、向文件中写入数据、移动文件指针以及关闭文件。以下是这些函数的详细介绍和实际应用示例。
1. 创建和打开文件 (open)
open
函数简介
open
函数用于打开一个现有文件或创建一个新文件。当配合 O_CREAT
标志使用时,它可以创建一个新的文件。
函数原型
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags, ... /* mode_t mode */);
参数说明
pathname
: 要打开或创建的文件的路径。flags
: 控制文件打开或创建方式的标志,可以是:
O_RDONLY
:只读打开。O_WRONLY
:只写打开。O_RDWR
:读写打开。O_CREAT
:如果文件不存在,则创建它。O_EXCL
:与O_CREAT
一起使用时,如果文件已存在,则返回错误。O_TRUNC
:如果文件已存在并且是以写入方式打开,则清空文件。mode
(可选参数):指定新文件的权限。这个参数是在文件创建时设置的,通常与umask
的默认设置一起使用,例如0644
、0755
等。
示例代码:创建文件
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
int fd; // 文件描述符
// 创建文件,如果文件不存在。设置文件权限为 0644 (rw-r--r--)
fd = open("newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("创建文件失败");
exit(EXIT_FAILURE);
}
printf("文件 'newfile.txt' 已成功创建\n");
// 对文件进行写操作等
// ...
// 完成操作后,关闭文件
close(fd);
return 0;
}
2. 写入文件 (write
)
write
函数将数据写入文件。
函数原型
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
fd
:文件描述符,由open
返回。buf
:指向数据缓冲区的指针。count
:要写入的字节数。
示例代码:写入数据
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd;
fd = open("testfile.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);
if (fd == -1) {
perror("打开文件失败");
exit(EXIT_FAILURE);
}
char *data = "Hello, Ubuntu 文件编程!";
// 将字符串数据写入文件
if (write(fd, data, strlen(data)) == -1) {
perror("写入文件失败");
close(fd);
exit(EXIT_FAILURE);
}
printf("数据写入成功\n");
// 写入完毕,关闭文件
close(fd);
return 0;
}
3. 读取文件(read)
参数说明
fd
:文件描述符,表示要读取数据的文件。这个文件描述符通常是通过open
系统调用获取的。buf
:指向数据缓冲区的指针,用于存储从文件中读取的数据。count
:指定要读取的最大字节数。实际读取的字节数可能少于这个值,比如文件剩余内容不足count
字节时。返回值
- 返回读取的字节数,如果文件已到达末尾,则返回 0。
- 如果发生错误,则返回 -1,并设置
errno
以指示错误类型。
函数原型:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd; // 文件描述符
ssize_t bytes_read; // 实际读取的字节数
char buffer[1024]; // 数据缓冲区
// 打开文件
fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("打开文件失败");
exit(EXIT_FAILURE);
}
// 从文件中读取数据
bytes_read = read(fd, buffer, sizeof(buffer) - 1); // 保留一个位置用于放置字符串终止符'\0'
if (bytes_read == -1) {
perror("读取文件失败");
close(fd);
exit(EXIT_FAILURE);
}
buffer[bytes_read] = '\0'; // 确保读取的内容被正确终止以便作为字符串处理
// 打印读取的内容
printf("读取到的内容:\n%s\n", buffer);
// 关闭文件
close(fd);
return 0;
}