Linux 系统编程学习之文件编程

Linux 系统编程学习之文件编程

文件描述符

(1)在linux系统中,当打开或者创建一个文件时会返回一个文件描述符,在读写文件时,需要将文件描述符作为参数传递给相应的函数。
(2)文件描述符是一个非负整数,是一个索引值

打开(open)

   #include <sys/types.h>
   #include <sys/stat.h>
   #include <fcntl.h>

   int open(const char *pathname, int flags);
   int open(const char *pathname, int flags, mode_t mode);
   
   int creat(const char *pathname, mode_t mode);

const char *pathname 是文件的路径和文件名
falgs 作为参数可以作为文件的多个选项,O_RDONLY 只读, O_WRONLY 只写, O_RDWR 可读可写
mode_t mode 参数只在创建新文件的时候会使用到, 用于标志文件的权限,读(r)写(w)执行(x)分别对应权限值 4, 2, 1。

读(read)

   #include <unistd.h>

   ssize_t read(int fd, void *buf, size_t count);

fd 是通过open返回的文件描述符
buf 是读取文件后保存的地址
count 是读取文件的长度,返回值是实际读到的字节数
返回值ssize_t 为0时,说明已经达到文件的末尾,返回值为-1时,读取文件失败。

写(write)

   #include <unistd.h>

   ssize_t write(int fd, const void *buf, size_t count);

fd 是通过open返回的文件描述符
buf 是写入文件的地址
count 是写入文件的长度
返回值ssize_t 是实际写入的字节数,返回值为-1时,写入文件失败。

光标(lseek)

   #include <sys/types.h>
   #include <unistd.h>

   off_t lseek(int fd, off_t offset, int whence);

读写的过程的通过光标的移动完成的,每当读写完成后光标会停留在最后一个字节的末尾,可以通过 lseek 函数来实现光标的移动
fd是文件描述符
offset为光标的偏移值,是相对于whence位置的偏移值,向右为正,向左为负
whence为光标的位置,有三个位置可以设置,分别为文件头 SEEK_SET,当前位置 SEEK_CUR,文件尾 SEEK_END

关闭文件–close

   #include <unistd.h>

   int close(int fd);

fd – 文件描述符

代码段

创建并打开一个文件,并写入字符串,再读文件并打印出来

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
	int fd;
	char *buf = "hello world!";
	fd = open("./file", O_RDWR);
	if (fd < 0)
	{
		printf("%s\n", "打开失败");
		fd = open("./file", O_RDWR|O_CREAT,0200);
		if (fd > 0)
		{
			printf("%s\n","打开成功");
		}
	}
	int write_n = write(fd, buf, strlen(buf));
	printf("%d\n", write_n);
	lseek(fd, -12, SEEK_END);
	char *readBuf = (char *)malloc(sizeof(char)* write_n + 1);
	int read_n = read(fd, readBuf, write_n);
	printf("%s\n", readBuf);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值