分类: C/C++
2010-12-06 21:42:12
文件创建
#include
#include
#include
#include
#include
void create_file(char *filename){
/*创建的文件具有什么样的属性?*/
if(creat(filename,0755)<0){
printf("create file %s failure!\n",filename);
exit(EXIT_FAILURE);
}else{
printf("create file %s success!\n",filename);
}
}
int main(int argc,char *argv[]){
int i;
if(argc<2){
perror("you haven't input the filename,please try again!\n");
exit(EXIT_FAILURE);
}
for(i=1;i
create_file(argv[i]);
}
exit(EXIT_SUCCESS);
}
文件打开
#include
#include
#include
#include
#include
int main(int argc ,char *argv[]){
int fd;
if(argc<2){
puts("please input the open file pathname!\n");
exit(1);
}
//如果flag参数里有O_CREAT表示,该文件如果不存在,系统则会创建该文件,该文件的权限由第三个参数决定,此处为0755
//如果flah参数里没有O_CREAT参数,则第三个参数不起作用.此时,如果要打开的文件不存在,则会报错.
//所以fd=open(argv[1],O_RDWR),仅仅只是打开指定文件
if((fd=open(argv[1],O_CREAT|O_RDWR,0755))<0){
perror("open file failure!\n");
exit(1);
}else{
printf("open file %d success!\n",fd);
}
close(fd);
exit(0);
}
文件复制
#include
#include
#include
#include
#define BUFFER_SIZE 1024
int main(int argc,char **argv)
{
FILE *from_fd;
FILE *to_fd;
long file_len=0;
char buffer[BUFFER_SIZE];
char *ptr;
/*判断入参*/
if(argc!=3)
{
printf("Usage:%s fromfile tofile\n",argv[0]);
exit(1);
}
/* 打开源文件 */
if((from_fd=fopen(argv[1],"rb"))==NULL)
{
printf("Open %s Error\n",argv[1]);
exit(1);
}
/* 创建目的文件 */
if((to_fd=fopen(argv[2],"wb"))==NULL)
{
printf("Open %s Error\n",argv[2]);
exit(1);
}
/*测得文件大小*/
fseek(from_fd,0L,SEEK_END);
file_len=ftell(from_fd);
fseek(from_fd,0L,SEEK_SET);
printf("from file size is=%d\n",file_len);
/*进行文件拷贝*/
while(!feof(from_fd))
{
fread(buffer,BUFFER_SIZE,1,from_fd);
if(BUFFER_SIZE>=file_len)
{
fwrite(buffer,file_len,1,to_fd);
}
else
{
fwrite(buffer,BUFFER_SIZE,1,to_fd);
file_len=file_len-BUFFER_SIZE;
}
bzero(buffer,BUFFER_SIZE);
}
fclose(from_fd);
fclose(to_fd);
exit(0);
}