ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

C语言文件读写

2022-05-06 23:00:51  阅读:178  来源: 互联网

标签:文件 old 读写 argv C语言 fd return include


open() read() write()

样例:将旧文件复制为新文件

/** 
	复制一个文件 
				 **/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
 
 //步骤:打开目标文件->读取目标文件->创建新文件->写入新文件
 
// 执行:./copy [filename0] [filename1]

int main(int argc, char **argv)		//argc为长度,argv为内容
{
	int fd_old, fd_new;	//新文件和旧文件的变量
	
	//read()函数要用到的参数
	char buf[1024];		//缓冲区大小
	int len;			//读取的文件的长度
	
	//错误输入
	if(argc != 3){		//命令参数不为3则退出
		printf("Usage: %s <old-file> <new-file>\n", argv[0]);
		return -1;
	}
	
	//打开目标文件
	fd_old = open(argv[1] , O_RDWR);	//用可读可写的方式打开目标文件(rdonly)
	if(fd_old == -1){
		printf("can not open the file %s\n", argv[1]);
		return -1;
	}
	
	//读取目标文件
	len = read(fd_old, buf, 1024);
	if(len == -1){
		printf("can not read the file %s\n", argv[1]);
		return -1;
	}
	
 	//创建新文件
	fd_new = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
	
	/*
	O_RDWD:可读写
	O_CREAT:创建文件
	O_TRUNC:将原文件内容丢弃大小置为0
	参数3:用户、组、其他的权限设置
	*/
	
	//写入新文件
	len = write(fd_new, buf, len); 
	if(len == -1){
		printf("can not write the file %s\n", argv[1]);
		return -1;
	}
	return 0;
}

进阶

通过内存映射的方式读取文件并写入

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>

/*
	执行:./copy_mmap [filename0] [filename1]

*/

int main(int argc, char **argv)
{
	int fd_old, fd_new;
	int len = 0;
	char *buf;
	struct stat stat;
	
	//输出错误
	if(argc != 3){
		printf("Usage: %s [filename0] [filename1]\n", argv[0]);
		return -1;
	}
	
	fd_old = open(argv[1], O_RDWR);	//返回值为一个文件描述符,Linux的文件描述符是一个非负整数
	if(fd_old == -1){
		printf("Can not open %s\n", argv[1]);
		return -1;
	}
	
	//通过确定文件状态的方式来排除太大的文件?
	if(fstat(fd_old, &stat) == -1){
		printf("Can not get stat of file %s\n", argv[1]);
		return -1;
	}
	//通过内存映射的方式将fd_old的内容存入缓冲变量buf
	//buf = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd_old, 0);//标准写法
	buf = mmap(NULL, 1024, PROT_READ, MAP_SHARED, fd_old, 0);
	//创建新文件
	fd_new = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
	
	//将缓冲变量写入新文件
	//len = write(fd_new, buf, stat.st_size);//标准写法
	len = write(fd_new, buf, 1024);
	
	return 0;
}

标签:文件,old,读写,argv,C语言,fd,return,include
来源: https://www.cnblogs.com/zanerogl/p/16240403.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有