Linux文件编程(二)

Linux文件打开及创建(二)

文件写入函数write

头文件:
#include <unistd.h>

函数原型:
ssize_t write(int fd, const void *buf, size_t count);

参数:
fd:文件标识符指向所需要写入的文件

const void *buf:缓冲区,需要写入的字符串存储的空间,将其提取出来写入文件中

size_t count:写入多少个字节

返回值:
写入字节个数

读取函数read

头文件:
#include <unistd.h>

函数原型:
ssize_t read(int fd, void *buf, size_t count);

参数:
fd:文件标识符指向所需要读取的文件

void *buf:缓冲区,把读取到的内容存放在一个堆区中

size_t count:需要读取的大小

返回值:
读取的字节数大小

create函数

原型:

int creat(const char *filename,mode_t mode)

filename:要创建的文件名(包含路径,缺省为当前路径)
mode:创建模式(open函数的mode参数也适用)

/*文件所有者权限*/
#define S_IRWXU 00700	//可读可写可执行
#define S_IRUSR 00400	//可读
#define S_IWUSR 00200	//可写
#define S_IXUSR 00100	//可读

/*用户组权限*/
#define S_IRWXG 00070
#define S_IRGRP 00040
#define S_IWGRP 00020
#define S_IXGRP 00010


/*其它用户权限*/
#define S_IRWXO 00007
#define S_IROTH 00004
#define S_IWOTH 00002
#define S_IXOTH 00001

文件读写的实际代码案例

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


int main()
{
	int fd;		//文件指向符
	char *buf="WPR!";		//缓冲区,需要写入的内容存放在这里
	fd = open("./file 1",O_RDWR);	//打开file 1 以可读可写的模式打开
	if(fd == -1)
	{
		printf("open file 1 faile\n");
		fd = open("./file 1",O_RDWR|O_CREAT,0600);		//打开创建文件
		if(fd>0)
		{
			printf("creat file 1 success\n");
		}
	}

	printf("open success :fd=%d\n",fd);
	
	int n_write=write(fd,buf,strlen(buf));
	if(n_write != -1)
	{
		printf("write %d byte to file 1 \n",n_write);		//write 函数返回的是写入的字符串字节数
	}
	
	close(fd);
	
	fd=open("./file 1",O_RDWR);		//关闭并重新打开文件,目的是让光标移到开头
	
	
	char *readBuf;
	readBuf=(char *)malloc(sizeof(char)*n_write+1);//给readBuf开辟空间存放,write的内容
	int n_read=read(fd,readBuf,n_write);
	printf("read %d ,context:%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、付费专栏及课程。

余额充值