- 论坛徽章:
- 0
|
首先推荐一个网址,讲解非常详细。
具体的函数原型如下:
#include
#include
#include
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
返回值:成功返回新分配的文件描述符,出错返回-1并设置errno
#include
ssize_t read(int fd, void *buf, size_t count);
返回值:成功返回读取的字节数,出错返回-1并设置errno,如果在调read之前已到达文件末尾,则这次read返回0
#include
ssize_t write(int fd, const void *buf, size_t count);
返回值:成功返回写入的字节数,出错返回-1并设置errno
主要是讲解我写的一段程序,过程中遇到的问题:
/*
* =====================================================================================
*
* Filename: fileTest.c
*
* Description: file create operation test
*
* Version: 1.0
* Created: 2009年04月06日 11时11分53秒
* Revision: none
* Compiler: gcc
*
* Author: Dr.Wupeng (mn), wpdzyx@126.com
* Company: SunLinux
*
* =====================================================================================
*/
#include
#include
#include
#include
#include
#include
#include
#define STD_INPUT 0
#define STD_OUTPUT 1
#define STD_ERROR 2
const char* filename = "log.txt";
int creatNewFile()
{
int fd;
//const char* filename = "log.txt";
if(access(filename,F_OK) == 0)
{
printf("file already exist,delete and then create\n");
unlink(filename);
}
fd = open(filename,O_RDWR|O_CREAT,S_IWUSR|S_IRUSR);
if(fd == -1)
{
perror("creat file");
}
write(fd,filename,sizeof(filename));
symlink("./log.txt","symlink");
close(fd);
return;
}
int lseekReadFile()
{
int fd;
off_t offset;
//const char* filename = "a.txt";
char* content = "this is a file operation test of lseek func,\
please do not care if there is some error\n";
char buffer[128];
fd = open(filename,O_RDWR);
printf("fd:%d\n",fd);
//chmod(filename,O_RDWR);
if(fd == -1)
{
perror("error happend");
}
write(fd,content,strlen(content));
offset = lseek(fd,0,SEEK_SET);
read(fd,buffer,strlen(content));
write(STD_OUTPUT,buffer,sizeof(buffer));
return;
}
int main()
{
creatNewFile();
lseekReadFile();
return 1;
}
主要的一点是read/write操作后,文件的读写位置会到文件的末尾,此时如果在写操作后,如果想再读出刚才写入的内容
需要将文件和读写位置重新设定为文件开始或写入的位置。此时要用到lseek函数,用法如下:
#include
#include
off_t lseek(int fildes,off_t offset ,int whence);
欲将读写位置移到文件开头时:lseek(int fildes,0,SEEK_SET);
欲将读写位置移到文件尾时:lseek(int fildes,0,SEEK_END);
想要取得目前文件位置时:lseek(int fildes,0,SEEK_CUR);
如果不注意此点问题,则读出的内容全是乱的,根本不是你想要的;
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/81187/showart_1891650.html |
|