借用别人的一句话:
说到文件 IO 编程,那当然首先要来谈一谈在 Linux 操作系统里,什么是文
件?记得以前说过,在 Linux 中,几乎一切都可以看做是文件。串口、打印机、
硬盘等设备都可以看做是文件,学过驱动的应该都知道/dev/xxx 都是设备文件。
大多数情况下,这些文件都会涉及的函数接口一般有以下 5 个,open,
read,write,ioctl,close。有人也许会说,目录也是文件吗?没错,目录在 Linux 环
境下确实是一个文件,只不过打开目录文件,用的函数不再是 open/read 而是
opendir/readdir 接口来读取目录。另外,应用程序工程师不必了解上面提到的系
统接口函数是如何实现的。总结一下:Linux 中的文件主要分为 4 种:普通文件、
目录文件、链接文件和设备文件。
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc ,char **argv)
{
int fd,size;
char *buf = "hello,I'm Webee,This is file io test!";
char buf_r[20];
int len = strlen(buf);
/* 首先调用 open 函数,如果当前目录下没有 hello.c 则创建
* 以读写方式打开文件,并指定权限为可读可写
*/
if((fd = open("./hello.c",O_CREAT | O_TRUNC | O_RDWR,0666))<0)
{
/* 错误处理 */
printf("open fail\n");
exit(1);
}
else
printf("open file:hello.c fd = %d\n",fd);
/* 调用 write 函数,将 buf 中的内容写入 hello.c */
if((size = write(fd,buf,len) ) < 0)
{
printf("write fail\n");
exit(1);
}
else
printf("write: %s\n",buf);
printf("len is %d ",len);
/* 调用 lseek 函数将文件指针移到文件起始位置,并读出文件中的 15 个字
节 */
lseek(fd,0,SEEK_SET);
if((size = read(fd,buf_r,15)) <0)
{
printf("read fail\n");
exit(1);
}
else
{
buf_r[15] = '\0';
printf("read from hello.c and the content is %s\n",buf_r);
}
/* 最后调用 close 函数关闭打开的文件 */
if(close(fd) < 0)
{
printf("close fail\n");
exit(1);
}
else
printf("close hello.c\n");
return 0;
}