系统IO 编写copy程序 简析对文件的操作
2015-03-17 21:34
155 查看
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char **argv)
{
//判断参数个数是否正确
if(argc != 3)
{
printf("Usage: %s <src> <dst>\n", argv[0]);
exit(1);
}
// 利用open函数打开文件,并返回文件描述符
int fd1 = open(argv[1], O_RDONLY);
if(fd1 < 0)
{
printf("open(argv[1]) is failed!:%s \n", argv[1], strerror(errno));
exit(1);
}
int fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0777);
if(fd2 < 0)
{
printf("open(argv[2]) is failed!:%s \n", argv[2]);
exit(1);
}
int nread, nwrite;
char *buf = malloc(200);
//不断地读写argv[1]中的内容并写入argv【2】,当满足条件时分别执行相应操作
while(1)
{
while((nread = read(fd1, buf, 200)) == -1 && errno == EINTR)
if(nread == -1)
{
printf("read() hits a real error: %s\n", strerror(errno));
exit(1);
}
if(nread == 0)
break;
char *p = buf;
//读取文件时有数据返回则执行一下循环。
while(nread > 0)
{
nwrite = write(fd2, p, nread);
nread -= nwrite;
p += nwrite;
}
}
//关闭文件
close(fd1);
close(fd2);
exit(0);
}
关于这个小程序所用到的文件操作函数中的参数,可以再Ubuntu下使用命令查看。如 man 2 open
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char **argv)
{
//判断参数个数是否正确
if(argc != 3)
{
printf("Usage: %s <src> <dst>\n", argv[0]);
exit(1);
}
// 利用open函数打开文件,并返回文件描述符
int fd1 = open(argv[1], O_RDONLY);
if(fd1 < 0)
{
printf("open(argv[1]) is failed!:%s \n", argv[1], strerror(errno));
exit(1);
}
int fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0777);
if(fd2 < 0)
{
printf("open(argv[2]) is failed!:%s \n", argv[2]);
exit(1);
}
int nread, nwrite;
char *buf = malloc(200);
//不断地读写argv[1]中的内容并写入argv【2】,当满足条件时分别执行相应操作
while(1)
{
while((nread = read(fd1, buf, 200)) == -1 && errno == EINTR)
if(nread == -1)
{
printf("read() hits a real error: %s\n", strerror(errno));
exit(1);
}
if(nread == 0)
break;
char *p = buf;
//读取文件时有数据返回则执行一下循环。
while(nread > 0)
{
nwrite = write(fd2, p, nread);
nread -= nwrite;
p += nwrite;
}
}
//关闭文件
close(fd1);
close(fd2);
exit(0);
}
关于这个小程序所用到的文件操作函数中的参数,可以再Ubuntu下使用命令查看。如 man 2 open
相关文章推荐
- C程序(scanf函数应用、字符串中取小数、两文件COPY、指针操作、stdout、stdin、stderr、sscanf、sprintf函数)
- 关于PE病毒编写的学习(6)——关于PE文件结构操作的程序编写
- 关于PE病毒编写的学习(六)——关于PE文件结构操作的程序编写
- 设计一程序(Copy.java),可以实现文件的复制操作
- 关于PE病毒编写的学习(六)——关于PE文件结构操作的程序编写
- 出现“烫”“屯”字样,则说明你的程序是VC编写的DEBUG版程序,“烫”是未初始化的栈空间,“屯”是申请后未做过内存清零或COPY的堆内存。 写入文件是“屯”,则需要找下你申请的内存是不是没经过内存复
- 关于PE病毒编写的学习(六)——关于PE文件结构操作的程序编写
- 编写文件搜索小程序:1. 输入绝对路径以及搜索关键字,2. 搜索指定路径下(包括子文件夹)中名称包含关键字的所有文件并打印出,3. 将当前操作记录日志
- 错误提示:以前的某个程序安装已在安装计算机上创建挂起的文件操作。运行安装程序之前必须重新启动计算机
- 在C++Builder中编写发送图象文件程序(二)
- 编写一个对文件按字节写入的程序floppyWrite.exe
- 用MFC编写vega程序的原始工程文件
- 某个程序安装已在安装计算机上创建挂起的文件操作的解决办法(sql server)
- "某个程序安装已在安装计算机上创建挂起的文件操作" 解决办法 另解
- 在C++Builder中编写发送图象文件程序(四)
- "某个程序安装已在安装计算机上创建挂起的文件操作" 解决办法 另解
- 某个程序安装已在安装计算机上创建挂起的文件操作" 解决办法
- 在C++Builder中编写发送图象文件程序(三)
- 用servlet编写的文件上传程序
- 关于:以前的某个程序安装已在安装计算机上创建挂起的文件操作 解决办法