#Linux系统编程(close函数,read函数,write函数)

本文详细介绍了在Ubuntu16.04.7环境中,如何使用close(),open(),read(),write()等函数进行文件操作,包括文件的打开、关闭、读取和写入,并提供了相应的代码实例和终端命令说明。
摘要由CSDN通过智能技术生成

(一)发行版:Ubuntu16.04.7


(二)记录:

close函数

关闭fd标识符的文件

(1)close函数具有返回值

(2)包含头文件 

 (3)编译运行

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

int main(int argc,char *argv[])
{
//argc 表示命令行中参数的个数
//argv 表示命令行中的参数

int fd;  
int close_fd;

//没有a.c所以创建a.c
fd = open("a.c",O_CREAT|O_RDWR,0666);

if(fd == -1)
	printf("fail to open a.c\n");
else
	printf("open a.c successfully:%d\n",fd);

//关闭文件
close_fd=close(fd);   

if(close_fd == 0)
	printf("close a.c successfully\n");
else
	printf("fail to close a.c\n");


return 0;
}








read函数

将fd标识文件中count字节大小的数据拷贝到buf。

(1)参数:

(2)返回值:ssize_t

(3)编译运行

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

int main(int argc,char *argv[])
{
//argc 表示命令行中参数的个数
//argv 表示命令行中的参数

int fd;  
int close_fd;
ssize_t read_byte;
char read_buf[32]={0};

//没有a.c所以创建a.c
fd = open("readme.txt",O_RDWR);

if(fd == -1)
	printf("fail to open readme.txt\n");
else
	printf("open readme.txt successfully:%d\n",fd);

//读取文件
read_byte=read(fd,read_buf,32);

if(fd == -1)
	printf("fail to read readme.txt");
else
  {
    printf("read %d bytes\n",read_byte);
	for(int i=0;i<32;i++)
	printf("%c",read_buf[i]);
	printf("\n");
  }

//关闭文件
close_fd=close(fd);   

if(close_fd == 0)         
	printf("close file successfully\n");
else
	printf("fail to close file\n");


return 0;
}








write函数 (写入数据之后需要关闭文件,再打开文件才能读)

(1)参数:

(2)返回值:

(3)编译运行:

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

int main(int argc,char *argv[])
{
int fd;  
int close_fd;
ssize_t read_byte;
ssize_t write_byte;
char read_buf[11]={0};
char write_buf[11]="hello world";

fd = open("writeme.txt",O_RDWR|O_CREAT,0666);

if(fd == -1)
	printf("fail to open writeme.txt\n");
else
	printf("open writeme.txt successfully:%d\n",fd);

//写入数据
write_byte=write(fd,write_buf,11);
if(write_byte == -1)
	printf("fail to write\n");
else
	printf("write %d bytes successfully\n",write_byte);

//关闭文件
close_fd=close(fd);   

if(close_fd == 0)         
	printf("close file successfully\n");
else
	printf("fail to close file\n");

return 0;
}

(4)如果要在终端打印hello

write(1,"hello\n",6);

 因为 0 1 2分别代表的是

0---------------------------标准输入

1---------------------------标准输出

2---------------------------标准出错


(三)命令:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值