creat.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd;
fd = creat("hello.c",S_IRWXU);
if(-1 == fd)
{
perror("creat");
exit(1);
}
return 0;
}
open.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if 0
int main()
{
int fd;
int ret;
char buf[32]={0};
// fd = open("hello.c",O_RDWR); //以读写方式打开存在的文件
// 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 == fd)
{
perror("write");
exit(1);
}
lseek(fd,0,SEEK_SET); //相对文件开头移动的字节
// lseek(fd,strlen(buf) * -1,SEEK_CUR); //相对文件当前位置移动的字节
// lseek(fd,strlen(buf) * -1,SEEK_END); //相对文件末尾移动的字节
memset(buf,0,sizeof(buf));
ret = read(fd,buf,sizeof(buf));
if(-1 == ret)
{
perror("read");
exit(1);
}
printf("read from txt:%s\n",buf);
close(fd);
return 0;
}
#endif
#if 1
int main(int argc,char *argv[])
{
int fd_from,fd_to;
int ret;
char buf[32]={0};
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");
exit(1);
}
else if(0 == ret)
{
printf("拷贝结束\n");
break;
}
ret = write(fd_to,buf,ret);
if(-1 == ret)
{
perror("write");
exit(1);
}
memset(buf,0,sizeof(buf));
}
close(fd_from);
close(fd_to);
return 0;
}
#endif
fopen.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
fp = fopen("hello.txt","a+");
if(NULL == fp)
{
perror("fopen");
exit(1);
}
char buf[32] = "helloworld";
int ret;
ret = fwrite(buf,1,strlen(buf),fp);
if(0 == ret)
{
perror("fwrite");
exit(1);
}
fseek(fp,0,SEEK_SET);
memset(buf,0,sizeof(buf));
ret = fread(buf,1,sizeof(buf),fp);
if(0 == ret)
{
perror("fread");
exit(1);
}
printf("read from txt:%s\n",buf);
fclose(fp);
return 0;
}
lseek.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char * argv [ ])
{
int length;
/* int fd = open(argv[1],0,O_RDWR);
if(-1 == fd)
{
perror("open");
exit(1);
}
length = lseek(fd,0,SEEK_END);
printf("%d\n",length);
close(fd);*/
FILE *fp = fopen(argv[1],"a+");
if(NULL == fp)
{
perror("fopen");
exit(1);
}
fseek(fp,0,SEEK_END);
length = ftell(fp);
printf("%d\n",length);
fclose(fp);
return 0;
}
文件操作的库内的函数open,read,write,close,seek和fopen,fread,fwrite,fclose,fseek,ftell,前面不带f的是非缓冲文件的操作,带f的是缓冲文件的操作,主要区别就是内存和系统之间是否存在缓冲区,且缓冲区若遇到换行则将缓冲区的内容刷新至文件中,这个文件就是显示器抽象成的文件,他会显示缓冲区中刷新出来的内容。
open是如果有文件则打开文件,如果没文件则先创建文件后打开,且需要给该文件权限,fopen则是在后面加上对应的条件,a为清空后添加,a+为后面累加。
fwrite是将数据写进一个文件中,fread和fwrite对于read来说只是后面括号中的格式不同。