时间:2015年10月26日
主题:linux文件系统读写练习
参考资料:宋敬彬《Linux网络编程》
系统环境:ubuntu 13.10 + gcc
代码;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
/*
安全打开文件
int main(void)
{
char filename[] = "test.txt";
int fd = -1;
fd = open(filename,O_RDWR|O_EXCL|O_CREAT,S_IRWXU);
if (fd == -1)
{
printf("file %s exist!,reopen it \n",filename);
fd = open(filename,O_RDWR);
printf("fd : %d \n",fd);
}
else
{
printf("Open file %s success!,fd: %d \n",filename,fd);
}
return 0;
}
*/
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int fd=-1;
char filename[] = "test.txt";
char buf[] = "another one two check,another song for the radio";
int size = -1;
int i;
char temp[10];
fd = open(filename,O_RDWR);
if (fd == -1)
{
printf("file %s is exist !,reopen it \n",filename);
fd = open(filename,O_RDWR);
size = write(fd,buf,strlen(buf));
printf("write %d bytes into file %s,fd : %d \n",size,filename,fd);
}
close (fd);//确保数据已经被保存到文件
fd = open(filename,O_RDWR);
//读出刚刚写入的数据,看是否正确
while(size)
{
size = 0;
size = read(fd,temp,10);
if (size >0 )
{
printf("\"");
for (i=0;i<size;i++)
printf("%c",temp[i]);
printf("\"\n");
}
else
printf("reach the end of file %s ,fd is : %d \n",filename,fd);
}
return 0;
}
几点说明:
- open()函数的调用必须包含头文件sys/types.h、sys/stst.h、fcntl.h
- open(filename,flag,mode)函数不仅可以打开狭义上的文件,还能打开设备,此时filename代表设备描述符,例如”/dev/sdc”
- flag变量和mode变量配合使用可以安全的打开一个文件,通常flag设置为(O_CREAT|O_RDWR|O_EXCL),而mode仅在O_CREAT有效时才设置。当文件filename不存在时,O_CREAT有效,函数会新建一个mode权限的文件,如果此时filename文件存在,该函数在执行时会报错,即通过O_EXCL和O_CREAT同时设置时函数的返回值,来检测文件是否存在,如果在文件存在的条件下设置O_CREAT,则函数会返回-1,如果文件不存在而设置O_CREAT,则会按照参数指定的格式创建文件。
- 关于文件描符,linux系统保留0(标准输入)、1(标准输出)、2(标准错误)三个编号,而文件描述符则从3开始递增。如果不正常关闭已经打开的文件,则该序号会一直递增直到1023(最大值)。
- read(fd,buf,count)函数使用必须包含头文件unidtd.h。如果达到文件末尾,函数返回0。如果读入的数据不大于缓冲区大小则返回实际读到的字节数;否则,返回缓冲区大小,但是缓冲区内的数据截断后的数据。
- write()函数与read()函数类似,只是函数执行后,数据只是写到缓冲区而不是真正的文件,可以调用fsync()将数据写入设备。