C文件操作

C语言中对文件操作主要有open,write,read三个函数,最近复习到这几个函数,故顺便写了一个demo回顾回顾。

#include <stdio>    
#include <fcntl.h>
#include <io.h>
int main(int argc, char *argv[])
{
	int fd,ret;
	char content[]="this is test word",buf[1024];
	fd=open("C:\\Users\\yxx\\Desktop\\test.txt",O_CREAT|O_WRONLY);
	if(fd==-1)
	{
		printf("open failure\n");
		return -1;
	}
	ret=write(fd,content,sizeof(content));
	if(n==-1)
	{
		printf("write failure\n");
		close(fd);
		return -1;
	}
	close(fd);
	fd=open("C:\\Users\\yxx\\Desktop\\test.txt",O_RDONLY);
	ret=read(fd,buf,sizeof(buf));
	if(ret==-1)
	{
		printf("read failure\n");
		close(fd);
		return -1;
	}
	close(fd);
	printf("%s\n",buf);
	return 1;
}

C语言中对文件操作还有三个很类似的函数,fopen,fwrite,fread三个函数,我也写了一个demo

#include <stdio>
int main()
{
	FILE *fp;
	fp=fopen("test.txt","w+");
	char buf[]="this is test word";
	if(fp==NULL)
	{
		printf("open failure");
		return -1;
	}
	fwrite(buf,sizeof(buf),1,fp);
	fclose(fp);
	fp=fopen("test.txt","r+");
	char content[1024];
	if(fp==NULL)
	{
		printf("open failure");
		return -1;
	}
	fread(content,sizeof(content),1,fp);
	fclose(fp);
	printf("%s\n",content);
	return 1;
}


如果想了解更多文件操作的函数,可以访问http://see.xidian.edu.cn/cpp/html/238.html


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值