文件读取操作(linux系统编程)

  • read函数
    man手册介绍
    在这里插入图片描述
  • 代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main()
{
	int fd;
	int n_open;
	int n_write;
	int n_read;
	char *Buf="hello ubuntu";
	fd=open("./file2",O_RDWR);
	if(fd == -1){
		printf("没有该文件,等待创建.....\n");
		fd=open("./file2",O_RDWR|O_CREAT,0600);
		if(fd > 0){
			printf("创建成功并打开,fd=%d\n",fd);
		}
	}
	
	n_write=write(fd,Buf,strlen(Buf));
	if(n_write != -1){
		printf("写入成功,写了%d个字节\n",n_write);
	}
	char *readBuf;//定义一个缓冲区
	readBuf=(char *)malloc(sizeof(char)*n_write+1);//n_write是写入的字节数,readBuf大小就是写入了多少个字节数,加1保险点
	// ssize_t read(int fd, void *buf, size_t count);
	n_read=read(fd,readBuf,sizeof(readBuf));
	if(n_read != 0){
		printf("read %d个字节,内容是:%s\n",n_read,readBuf);
	}
	close(fd);	
	return 0;
}
  • 结果出现问题
    在这里插入图片描述
    说明此时的n_read=-1;那是什么原因呢,在接下的学习中发现时光标的问题。(代码中当写完后光标停留在ubuntu的末尾u后面,所以是读不到)
  • 文件光标
    在这里插入图片描述
lseek(int fd, off_t offset, int whence);//文件描述符,对wherence的偏移值,相对位置(固定位置)

 SEEK_SET
      The file offset is set to offset bytes.

 SEEK_CUR
      The file offset is set to its current location plus offset bytes.

 SEEK_END
      The file offset is set to the size of the file plus offset bytes.

-SEEK_SET指向文件的头
-SEEK_END指向文件的尾部
-SEEK_CUR指向文件的当前位置

  • 可以利用这个光标来计算文件的大小
    代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main()
{
	int fd;
	
	fd=open("./file2",O_RDWR);
	int fileSize=lseek(fd,0,SEEK_END);
	printf("大小为%d\n",fileSize);
	return 0;
}

  • 加了光标后的代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main()
{
	int fd;
	int n_open;
	int n_write;
	int n_read;
	char *Buf="hello ubuntu";
	fd=open("./file2",O_RDWR);
	if(fd == -1){
		printf("没有该文件,等待创建.....\n");
		fd=open("./file2",O_RDWR|O_CREAT,0600);
		if(fd > 0){
			printf("创建成功并打开,fd=%d\n",fd);
		}
	}
	
	n_write=write(fd,Buf,strlen(Buf));
	if(n_write != -1){
		printf("写入成功,写了%d个字节\n",n_write);
	}
	//lseek(int fd, off_t offset, int whence);
	lseek(fd,0,SEEK_SET);//光标指向头部也可以写成lseek(fd,-12,SEEK_END/CUR);
	char *readBuf;//定义一个缓冲区
	readBuf=(char *)malloc(sizeof(char)*n_write+1);//n_write是写入的字节数,readBuf大小就是写入了多少个字节数,加1保险点
	// ssize_t read(int fd, void *buf, size_t count);
	n_read=read(fd,readBuf,n_write);//把fd的内容放到readBuf里面进行读取,读了n_write个
	if(n_read != 0){
		printf("read %d个字节,内容是:%s\n",n_read,readBuf);
	}
	close(fd);	
	return 0;
}

结果
在这里插入图片描述

-坚持的第三天,继续冲冲冲

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值