当前位置: 技术问答>linux和unix
关于文件的读写
来源: 互联网 发布时间:2015-11-17
本文导语: #include #include #include #include int main( ) { int fd, size; char s[ ] = "Linux Programmer !", buffer[80]; fd = open (" hell", O_CREAT | O_RDWR | O_APPEND ); write(fd,s,sizeof(s)); close(fd); fd = open ("hell", O_RDONLY); ...
#include
#include
#include
#include
int main( )
{
int fd, size;
char s[ ] = "Linux Programmer !", buffer[80];
fd = open (" hell", O_CREAT | O_RDWR | O_APPEND );
write(fd,s,sizeof(s));
close(fd);
fd = open ("hell", O_RDONLY); //为什么我的文件打开失败
if( fd > 0 )
{
size = read(fd,buffer,sizeof(buffer));
close(fd);
printf("/n%d",sizeof(buffer));
}
else
printf( "Error");
return 0;
}
请高手指点一下.
#include
#include
#include
int main( )
{
int fd, size;
char s[ ] = "Linux Programmer !", buffer[80];
fd = open (" hell", O_CREAT | O_RDWR | O_APPEND );
write(fd,s,sizeof(s));
close(fd);
fd = open ("hell", O_RDONLY); //为什么我的文件打开失败
if( fd > 0 )
{
size = read(fd,buffer,sizeof(buffer));
close(fd);
printf("/n%d",sizeof(buffer));
}
else
printf( "Error");
return 0;
}
请高手指点一下.
|
创建文件可以使用creat函数
int creat(const char *pathname,mode_t mode);
但creat有一个不足,它是以只写方式打开所创建的文件,如果创建完以后要写,再读,则必须先调用close,然后再open.
所以一般用open创建来创建。
open(pathname,O_RDWR | O_CREAT | O_TRUNC, mode)
你在创建文件的时候,没有指定文件的权限,缺少了mode.:)
你给加上权限,就OK了。
int creat(const char *pathname,mode_t mode);
但creat有一个不足,它是以只写方式打开所创建的文件,如果创建完以后要写,再读,则必须先调用close,然后再open.
所以一般用open创建来创建。
open(pathname,O_RDWR | O_CREAT | O_TRUNC, mode)
你在创建文件的时候,没有指定文件的权限,缺少了mode.:)
你给加上权限,就OK了。
|
嗯,谢谢老兄的提醒,不过我在fd = open (" hell", O_CREAT | O_RDWR | O_APPEND )改为
fd = open (" hell", O_CREAT | O_RDWR | O_APPEND |S_IRWXU);后就可以打开了.
fd = open (" hell", O_CREAT | O_RDWR | O_APPEND |S_IRWXU);后就可以打开了.