第三阶段 第一章 文件操作
文件操作相关函数的使用
access 函数的使用
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char** argv)
{
if(argc < 2)
{
fprintf(stderr,"Usage <%s filepath>\n",argv[0]) ;
return -1;
}
if(-1 == access(argv[1],F_OK))
{
perror("access");
return -1;
}
printf("你所确认的文件存在\n");
return 0;
}
open函数的使用案例
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char** argv)
{
if(argc < 2)
{
fprintf(stderr,"Usage (%s filepath)\n",argv[0]);
return -1;
}
if(-1 == access(argv[1],F_OK))
{
int fd = open(argv[1],O_WRONLY | O_CREAT,0644);
if(fd == -1)
{
perror("open");
return -1;
}
}
else
{
int fd = open(argv[1],O_RDWR);
if(fd == -1)
{
perror("open");
return -1;
}
}
return 0;
}
read 函数的使用
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <strings.h>
int main(int argc,char** argv)
{
if(argc < 2)
{
fprintf(stderr,"Usage %s filepath\n",argv[0]);
return -1;
}
int fd = open(argv[1],O_RDONLY);
if(fd == -1)
{
perror("open");
return -1;
}
char buf[32] = {0};
ssize_t len = 0;
while(len = read(fd,buf,sizeof(buf)-1))
{
buf[len] = '\0';
printf("%s",buf);
}
close(fd);
return 0;
}
write函数的使用
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <strings.h>
int main(int argc,char** argv)
{
if(argc < 3)
{
fprintf(stderr,"Usage %s source dest\n",argv[0]);
return -1;
}
int fds = open(argv[1],O_RDONLY);
if(fds == -1)
{
perror("open");
return -1;
}
int fdd = open(argv[2],O_WRONLY|O_CREAT,0644);
if(fdd == -1)
{
perror("open");
close(fds);
return -1;
}
char buf[32] = {0};
ssize_t len = 0;
while(len = read(fds,buf,sizeof(buf)))
{
write(fdd,buf,len);
}
close(fds);
close(fdd);
return 0;
}