69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
char *path="../linuxtest/file.c";
char s[1024];
int fd;
extern int errno;
int size;
fd=open(path,O_RDWR,0766);
if(fd!=-1)
{
printf("file opened.\n");
}
else
{
printf("failed to open this file. PATH:%s\n",path);
printf("Error number:%d\n",errno);
printf("Error message:%s\n",strerror(errno));
}
lseek(fd,0,SEEK_SET);
size = read(fd,s,sizeof(s));
if(close(fd)==0)
{
printf("file closed.\n");
}
else
{
printf("cannot close the file. PATH:%s\n",path);
printf("Error number:%d\n",errno);
printf("Error message:%s\n",strerror(errno));
}
printf("the string read from that file is:%s",s);
printf("the size is :%d\n",size);
}
fileopen.c(之前是测试open()函数的,后来用来写数据到文件)
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd,fd1;
char path[]="../linuxtest/file.c";
extern int errno;
char buf[20];
char s[]="hello,linux.\nI've learned linux for two weeks.\n";
char s1[]="\nhi,this is my second time to write.";
fd = open(path,O_WRONLY,0766);
if(fd!=-1)
{
printf("file sucessfully opened. path:%s\n",path);
}
else
{
printf("cannot open the file. path:%s\n",path);
printf("errno:%d\n",errno);
printf("ERR:%d\n",strerror_r(errno,buf,20));
}
fd1 = open(path,O_WRONLY|O_CREAT,0766);
if(fd1!=-1)
{
printf("file successfully opened. path:%s\n",path);
}
else
{
printf("cannot open the file. path:%s\n",path);
printf("errno:%d\n",errno);
printf("ERR:%d\n",strerror_r(errno,buf,20));
}
write(fd,s,sizeof(s));
lseek(fd,0,SEEK_END);
write(fd,s1,sizeof(s1));
sync();
if(close(fd)==0)
{
printf("file closed. path:%s\n",path);
}
else
{
printf("cannot close the file. path:%s\n",path);
printf("errno:%d\n",errno);
printf("error message:%s\n",strerror(errno));
}
if(close(fd1)==0)
{
printf("file closed. path:%s\n",path);
}
else
{
printf("cannot close the file. path:%s\n",path);
printf("errno:%d\n",errno);
printf("error message:%s\n",strerror(errno));
}
printf("Done.\n");
}