open.c
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int fd;
int ret;
char buf[32] = {0};
/fd = open(“hello.c”,O_RDWR); //读写方式打开存在的文件
if(-1 == fd)
{
perror(“open”);
exit(1);
}
//fd = open("hello.txt",O_RDWR | O_CREAT,00700); //先创建文件,再打开,文件可以存在
fd = open("hello.txt",O_RDWR | O_CREAT | O_EXCL,00700); // 先创建文件,再打开,文件必须不存在
if(-1 == fd)
{
perror("open");
exit(1);
}
scanf("%s",buf);
ret = write(fd,buf,strlen(buf));
if(-1 == ret)
{
perror("write");
exit(1);
}
lseek(fd,strlen(buf) * -1,SEEK_END); //相对末尾位置向前移动x个位置
copy.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(int argc,char *argv[])
{
int ret;
int fd;
char buf[32] = {0};
int fd_from,fd_to;
fd_from = open(argv[1],O_RDONLY);
if(-1 == fd_from)
{
perror("open");
exit(1);
}
fd_to = open(argv[2],O_WRONLY | O_CREAT | O_EXCL,00700);
if(-1 == fd_to)
{
perror("open");
exit(1);
}
while(1)
{
ret = read(fd_from,buf,sizeof(buf)-1);
if(-1 == ret)
{
perror("read");
}
else if(ret == 0)
{
printf("拷贝完毕!\n");
break;
}
ret = write(fd_to,buf,ret);
if(-1 == ret)
{
perror("write");
}
memset(buf,0,sizeof(buf));
}
close(fd_from);
close(fd_to);
return 0;
}
lseek.c // 如何求文件长度
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
int length;
/*int fd = open(argv[1],O_RDWR);
if(-1 == fd)
{
perror(“open”);
exit(1);
}
length = lseek(fd,0,SEEK_END);//文件指针移动到文件末尾,返回移动后指针距离文件开头的长度*/
FILE *fp = fopen(argv[1],"a+");
if(NULL == fp)
{
perror("fopen");
exit(1);
}
fseek(fp,0,SEEK_END); //成功返回0
length = ftell(fp); //返回文件指针距离文件开头的长度
printf("%d\n",length);
return 0;
}
fopen.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *fp;
fp = fopen("justin.txt","a+");
if(NULL == fp)
{
perror("open");
exit(1);
}
char buf[32] = "helloworld";
int ret;
ret = fwrite(buf,1,strlen(buf),fp);
if(-1 == ret)
{
perror("fwrite");
exit(1);
}
fseek(fp,0,SEEK_SET);
memset(buf,0,sizeof(buf));
ret = read(buf,1,sizeof(buf),fp);
if(-1 == ret)
{
perror("read");
exit(1);
}
printf("read from txt : %s\n",buf);
close(fp);
return 0;
}