#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#define LENGTH 100
main(){
int fd,len;
char str[LENGTH];
fd=open("hello.txt",O_CREAT|O_RDWR|S_IWUSR,S_IWUSR);
if(fd)
{
write(fd,"hello word",strlen("hello word"));
close(fd);
}
fd=open("hello.txt",O_RDWR);
len=read(fd,str,LENGTH);
str[len]='\0';
printf("%s\n",str);
close(fd);
}
执行后打印的是乱码,给hello.txt权限了,再执行./a.out之后就能打印出hello word了,所以先看了open函数的各项参数的意思。原来是open函数的参数写错了,在第二项与第三项之间用了“|”,S_IRUSR|S_IWUSR表示的是任何人都可以读写。这样问题就解决了。之前都没哟仔细看。还需努力呀!
如果要打开固定路径的文件
#define PATH "/test/hello.txt"
open("PATH",xx,xx);
这样就可以了。