集训第一天

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值