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、结果展示
相关文章推荐
- 文件下载中input.read()与output.write()相关问题,以及mp3下载的文件比原文件大的解决方法
- Linux下使用open() read() write()进行文件读写及复制
- VBS读写文件以及OpenTextFile方法
- EntLib Validation Application Block 01 通过配置文件,自行指定对象自身方法进行验证
- Android的SD卡文件读写的帮助类——FileHelper,以及查询SD卡是否存在及其容量的方法
- CreateFile ReadFile WriteFile读写文件操作
- write to and read from files (读写文件)
- 在TFileListBox的子类里重写ReadFileNames那个虚方法(见filectrl.pas),根据文件创建时间进行排序。
- Linux下通过SSH快速的和本地进行文件的交互的方法
- Java基础之读文件——使用通道随机读写文件(RandomReadWrite)
- 读写文件节点---echo与read、write均可
- sys_read()/vfs_read()/vfs_write() Linux VFS文件系统之读写(read/write)文件
- 上传文件至FTP---通过FileUtils.writeByteArrayToFile()方法
- Dom解析是将xml文件全部载入,组装成一颗dom树,然后通过节点以及节点之间的关系来解析xml文件,下面结合这个xml文件来进行dom解析。
- Linux内核读写文件以及从SD卡读文件并处理的方法
- [perl] Spreadsheet::WriteExcel 和 Spreadsheet::Read 对 excel 文件的读写
- sys_read()/vfs_read()/vfs_write() Linux VFS文件系统之读写(read/write)文件
- java:File类中对文件或目录进行操作的常用方法以及遍历文件夹下面的文件
- 多线程读写文件利器-ReentrantReadWriteLock