努力学习Day13【Linux】

今天的学习的任务是,学习文件的读取

和之前的内容一样,我们需要使用终端命令来查看文件读取的一些编程格式

man 2 read

 

可以看到和我们之前看到的write等差不多,大同小异,于是乎我们就可以编写我们的代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>   //malloc函数,分配内存空间
int main()
{

	int fd;
	char *buf = "Hello Linux!"; 
	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("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);	
	}
	close(fd); //写入操作之后关闭
	fd = open("./file1",O_RDWR); //重新打开,去读取,使光标回到初始位置,以重新读取,不然光标在输入的最后一个字节后开始读取的话,就会发生错误,没办法读取光标前面的内容,所以需要重新打开,让光标回到初始位置
	char *readbuf;
	readbuf=(char *)malloc(sizeof(char)*n_write); //readbuf无类型指针,不指向哪个空间,需要使用malloc函数分配
	int n_read=read(fd,readbuf,n_write);
	printf("read: %d ,context: %s",n_read,readbuf);
	close(fd);
	return 0;
}

我们写完代码后,编译试试:

 read就是写入的字节数,context就是所输入的内容。

完成!

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值