文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>open/write/read系统调用学习

open/write/read系统调用学习

时间:2009-04-06  来源:wpdzyx

首先推荐一个网址,讲解非常详细。
具体的函数原型如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
返回值:成功返回新分配的文件描述符,出错返回-1并设置errno

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
返回值:成功返回读取的字节数,出错返回-1并设置errno,如果在调read之前已到达文件末尾,则这次read返回0

#include <unistd.h>

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), [email protected]
* Company: SunLinux
*
* =====================================================================================
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

#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<sys/types.h>
#include<unistd.h>
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);

如果不注意此点问题,则读出的内容全是乱的,根本不是你想要的;

相关阅读 更多 +
排行榜 更多 +
暗黑封魔录手游

暗黑封魔录手游

角色扮演 下载
战国美人游戏

战国美人游戏

角色扮演 下载
仙境苍穹手游

仙境苍穹手游

角色扮演 下载