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

Linux下使用open() read() write()进行文件读写及复制

2018-01-02 21:51 549 查看

代码

/*********************************************************************************
*      Copyright:  (C) 2018 None
*                  All rights reserved.
*
*       Filename:  main.c
*    Description:  Task_LO1
*
*        Version:  1.0.0(02/01/18)
*         Author:  atrouble <---------@qq.com>
*      ChangeLog:  1, Release initial version on "02/01/18 14:55:53"
*
********************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

#define SSIZE_MAX 10
/********************************************************************************
*  Description:    1 Creat a TXT named test.txt
*                  2 Write a string in the TXT
*                  3 Print the content
*                  4 Copy the TXT ,and named test.log
*   Input Args:    None
*  Output Args:    the content of file <test.txt>
* Return Value:    None
********************************************************************************/
int main (int argc, char **argv)
{
int  fd              = 0;
int  fd1             = 0;
char str[]           = "0123456789";
int  len             = 0;
char buf[SSIZE_MAX];

fd = open("test.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
write(fd, str, strlen(str));
close(fd);

fd = open("test.txt", O_RDONLY);
len = read(fd, buf, SSIZE_MAX);
printf("str : %s\n", str);
printf("buf : %s\nlen : %d\n", buf, len);
printf("test.txt : %s\n",buf);

fd1 = creat("test.log",0644);
write(fd1, buf, strlen(buf));

close(fd);
close(fd1);
return 0;
} /* ----- End of main() ----- */


运行结果

zlf@zlf:~/APUE$ ./a.out
str : 0123456789
buf : 0123456789
len : 10
test.txt : 0123456789


相关函数

#include<fcntl.h>
int open(constchar*pathname,intflags);
int open(constchar*pathname,intflags,mode_tmode);
返回值:成功则返回文件描述符,否则返回-1


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

read()会把参数 fd 所指的文件传送 count 个字节到 buf 指针所指的内存中。
若参数 count 为0,则 read 返回实际读取到的字节数,如果返回0,表示已到达文件尾或是无可读取的数据,此外文件读写位置会随读取到的字节移动。


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

write函数把 buf 中 nbyte 写入文件描述符 handle 所指的文档,成功时返回写的字节数,错误时返回-1.


使用注意

1、尤其注意文件描述符 fd ,在读写时候 fd 对应打开文件的状态是初始fd = open();时候给定的权限以及状态。

譬如在我read(“test.txt”….)时 不能直接用之前的fd,要重新申请。

2、注意调用read() write()时候的 str 、buf的定义类型,我之前定义是 char *str , *buf; 然后在执行时行会有指针报错,暂时没弄懂为啥,弄懂了再更新。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 linux