ubuntu学习(五)----读取文件以及光标的移动

1、读取文件函数原型介绍

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

参数说明:
fd: 是文件描述符
buf:为读出数据的缓冲区;
count:   为每次读取的字节数(是请求读取的字节数,读上来的数据保存在缓冲区buf中,同时文件的当前读写位置向后移)

返回值:

 成功:返回读出的字节数
 失败:返回-1,并设置errno,如果在调用read,之前到达文件末尾,则这次read返回0

2、读取文件函数示例  

打开终端,输入以下指令:

 vi demo2.c

 接着输入如下代码:

#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 fd;
	char *buf = "asdfgh!";	

	fd = open("./file1",O_RDWR);

	if(fd == -1){
		printf("open file1 failed\n");
		fd = open("./file1",O_RDWR|O_CREAT,0600);
		if(fd > 0){
			printf("create file1 success!\n");
		}
	}
	
	printf("open susceess : fd = %d\n",fd);

//	ssize_t write(int fd, const void *buf, size_t count);
	int n_write = write(fd,buf,strlen(buf));
	if(n_write != -1){
		printf("write %d byte to file\n",n_write);
	}

	char *readBuf;
	readBuf = (char *)malloc(sizeof(char)*n_write + 1);	
//	  ssize_t read(int fd, void *buf, size_t count);
	int n_read = read(fd, readBuf, n_write);
	
	printf("read %d ,context:%s\n",n_read,readBuf);
	close(fd);

	return 0;
}

保存退出后,输入如下指令:

gcc demo2.c 

./a.out

 3、光标移动操作

从运行结果可以看到,并未读取到内容,因为读取时候光标不在最左侧,因此需要进行光标设置。

 光标函数原型:

 off_t lseek(int fd, off_t offset, int whence);
  • 函数参数

    • fd:文件描述符

    • offset:偏移量

    • whence:位置

      • SEEK_SET:The offset is set to offset bytes. offset为0时表示文件开始位置。
      • SEEK_CUR:The offset is set to its current location plus offset bytes. offset为0时表示当前位置。
      • SEEK_END:The offset is set to the size of the file plus offset bytes. offset为0时表示结尾位置
  • 函数返回值

    • 成功返回当前位置到开始的长度
    • 失败返回-1并设置errno

 首先输入如下指令:

vi demo2.c

 输入以下代码:

#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 fd;
	char *buf = "asdfghi!";	

	fd = open("./file1",O_RDWR);

	if(fd == -1){
		printf("open file1 failed\n");
		fd = open("./file1",O_RDWR|O_CREAT,0600);
		if(fd > 0){
			printf("create file1 success!\n");
		}
	}
	
	printf("open susceess : fd = %d\n",fd);
	int n_write = write(fd,buf,strlen(buf));
	if(n_write != -1){
		printf("write %d byte to file\n",n_write);
	}

	char *readBuf;
	readBuf = (char *)malloc(sizeof(char)*n_write + 1);	

	lseek(fd, 0, SEEK_SET);

	int n_read = read(fd, readBuf,100);
	
	printf("read %d ,context:%s\n",n_read,readBuf);
	close(fd);

	return 0;
}

 保存,输入以下指令:

gcc demo2.c

./a.out

 运行结果如下:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值