文件I/O操作之文件的读写-基于Linux系统文件IO

时间:2014-09-03 00:04:45   收藏:0   阅读:499

1.

读取已经打开的文件

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

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

buf是一个指向缓冲区的指针,此缓冲区存放将要读取到终端的数据,count表示将要读取的字节数

2.

向打开的文件写数据

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

返回已经写入的字节数,出错返回-1

若指定O_APPEND选项,则每次写之前都定位到文件尾

 

示例:

 1 #include<stdio.h>
 2 #include<sys/types.h>
 3 #include<sys/stat.h>
 4 #include<fcntl.h>
 5 #include<unistd.h>
 6 #include<string.h>
 7 #include<stdlib.h>
 8 
 9 #define FILENAME "hello"
10 #define BUF_SIZE 80
11 #define FLAGS O_RDWR|O_APPEND
12 int main(void)
13 {
14     int count;
15     int fd;
16     char write_buff[BUF_SIZE];
17     const char *pathname=FILENAME;
18     if((fd=open(pathname,FLAGS))==-1)
19     {
20         printf("error");
21         exit(1);
22     }
23     printf("OK,has opened file\n");
24     printf("start to write:\n");
25 
26     scanf("%[^\n]",write_buff);
27 
28     count=strlen(write_buff);
29     if(write(fd,write_buff,count)==-1)
30     {
31         printf("error to write\n");
32         exit(0);
33     }
34     printf("OK has write to file\n");
35     return 0;
36 }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!