您的位置:首页 > 运维架构 > Linux

linux c通过文件描述符以及write和read方法对文件进行读写

2017-01-09 20:24 519 查看

1、write和read方法讲解

#include<unistd.h>
ssize_t read(int fd, void *buf,size_t count);

fd为文件描述符,buf缓冲区指针,count表示要读取的字节数

返回:读到的字节数,若已经到文件尾端返回0,出错返回-1

#include<unistd.h>
ssize_t write (int fd, void *buf, size_t count);


fd为文件描述符,buf缓冲区指针,count表示要写的字节数

返回:若成功已写的字节数,若出错为-1


2、代码实现读写

比如在/home/chenyu/Downloads/chenyu文件进行写和读

#include<sys/stat.h>
#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
//特么你这里要注意了,不需要写=号,字符串记得加双引号
#define FILEPATH "/home/chenyu/Downloads/chenyu"
#define SIZE 100
//读写方式打开,向文件添加内容从文件尾开始写
#define FLAGS O_RDWR | O_APPEND

int main()
{
int count = 0;
const char *pathname = FILEPATH;
printf("%s", pathname);
int fd;
char data[SIZE];
if ((fd = open(pathname, FLAGS)) == -1) {
printf("open file fail\n");
return 0;
}
printf("open file success\n");
printf("请输入字符串\n");
scanf("%s", data);
count = strlen(data);
printf("show data:%s\n", data);
printf("data length is %d\n", count);
if (write(fd, data, count) == -1) {
printf("write data fail\n");
return 0;
}
printf("write data success\n");
// close(fd);
fd = open(pathname, O_RDONLY);
char content[100];
read(fd, content, sizeof(content));
printf("chenyu content is %s\n", content);
return 0;
}


3、结果展示



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐