不带缓存是指每一个函数都只调用系统中的一个函数。主要有5个函数:open、read、write、lseek、close。因为在Linux中,所有都可以看作是一个文件,普通的文件、串口、socket等等,都可以作为文件处理。这样,在编程上就简化了很多。但是要注意lseek函数,它不能够用于socket。
下面编写了一个最为简单的例子,主要就是:打开文件->写入内容->读取内容->关闭文件。这个程序是很容易改进扩充的。
1、源代码
|
/* * Copyright (c) 2006, 山东大学 * All rights reserved. * * 文件名称:open.c * 文件摘要:学习IO函数。 * * 当前版本:1.0 * 作 者:刘庆敏 * 完成日期:2006/11/07 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h>
void die(char *msg) { perror(msg); exit(1); }
int open_file(void) { int fd;
if ((fd = open("/tmp/hello.c", O_CREAT | O_TRUNC | O_RDWR, 0666)) < 0) { die("open error"); } else { printf("Open file: hello.c %d\n", fd); }
return fd; }
void write_file(int fd, char *buf, int len) { if (write(fd, buf, len) < 0) { die("write error"); } else { printf("Write: %s\n", buf); } }
void read_file(int fd, int len) { char buff[len + 1];
lseek(fd, 0, SEEK_SET); if (read(fd, buff, len) < 0) { die("read error"); } else { buff[len] = '\0'; printf("read from file: %s\n", buff); } }
void close_file(int fd) { if (close(fd) < 0) { die("close error"); } else { printf("Close file: hello.c\n"); } }
int main(void) { int fd; char *buf="Hello! I`m writing to this file!"; int len = strlen(buf);
fd = open_file(); write_file(fd, buf, len); read_file(fd, len); close_file(fd);
return 0; }
|
2、运行情况:
|
[armlinux@lqm file_IO_program]$ make gcc -Wall -g open.c -o myopen [armlinux@lqm file_IO_program]$ ./myopen Open file: hello.c 3 Write: I`m writing to this read from file: I`m writing to this Close file: hello.c
|
3、注意问题
在子函数read_file中,尤其要注意数组buff[len + 1]绝对不可以写为buff[len]。假设写为buff[len],则会引起缓冲区溢出。这是安全编程不允许的。简单的分析一下。
因为要写入的字符串的长度是采用strlen函数来计算的,而strlen函数遇到'\0'就停止计数,不包括'\0'。而要用printf打印出字符串,要以\0结束。所以,实际上,buff的内存区长度为len+1。所以要设定为buff[len + 1]。
1.部分资源来自网络,经ET电子归类整理,旨在服务电子爱好者并无商业目的,不保证正确性与完整性.
2.如果您觉得本站资源对您有用,请告知您的好友,用搜索引擎搜"
ET电子"即可.