您的位置:首页 > 其它

收录一个拷贝文件的经典例子

2013-07-31 10:40 387 查看
在使用文件读写操作时,看到一个拷贝文件的经典例子,在此收录:

原文链接:http://lobert.iteye.com/blog/1705861

后面加入了我自己的例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFER_SIZE 1024

int main(int argc, char** argv,char** envpv){
int from_fd, to_fd;
int bytes_read, bytes_write;
char buffer[BUFFER_SIZE];
char *ptr;
if(argc != 3){
printf("Usage:%s fromfile tofile\n",argv[0]);
exit(0);
}
from_fd = open(argv[1], O_RDONLY);
if(from_fd < 0){
printf("File %s open failure!!!!\t Error num %s\n", argv[1], strerror(errno));
exit(1);
}

to_fd = open(argv[2], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if(to_fd < 0){
printf("File %s open failure!!!!\t Error num %s\n", argv[2], strerror(errno));
exit(2);
}
/* 以下代码是一个经典的拷贝文件的代码 */
while (bytes_read = read(from_fd, buffer, BUFFER_SIZE)) {
/* 一个致命的错误发生了 */
if ((bytes_read == -1) && (errno != EINTR)) break;
else if (bytes_read > 0) {
ptr = buffer;
while (bytes_write = write(to_fd, ptr, bytes_read)) {
/* 一个致命的错误发生了 */
if ((bytes_write == -1) && (errno != EINTR))break;
/* 写完了所有读的字节 */
else if (bytes_write == bytes_read) break;
/* 只写了一部分,继续写 */
else if (bytes_write > 0) {
ptr += bytes_write;
bytes_read -= bytes_write;
}
}
/* 写的时候发生的致命错误 */
if (bytes_write == -1)break;
}
}
close(from_fd);
close(to_fd);
return 0;
}


#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){

char buf[] ="I Am From China";
char tmp[20];
int fd = open("out.log", O_RDWR|O_CREAT, S_IRUSR | S_IWUSR);
if(fd < 0){
printf("Create file failure!!!!!!!\n");
exit(1);
}
write(fd,buf,sizeof(buf));
close(fd);
fd = open("out.log", O_RDONLY);
read(fd,tmp,sizeof(tmp));
close(fd);
printf("%s\n",tmp);
return 0;
}


补充一个例子(11/6/2013):

测试函数: fopen fclose fwrite fread

 

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1024

int main(int argc, char** argv, char** envp){
char buf[MAX_SIZE];
int rc;
FILE *input, *output;

if(argc < 3){
fputs("Usage: \"./case input output\" format\n", stdout);
exit(1);
}

input = fopen(argv[1], "rb");
output = fopen(argv[2], "wb");

if(input == NULL || output == NULL){
fputs("input or output pointer is NULL\n", stdout);
exit(1);
}

while((rc = fread(buf, sizeof(char), MAX_SIZE, input)) != 0)  //在这里应该注意优先级的问题,= 优先级低于 != ,所有要用括号
fwrite(buf, sizeof(char), rc, output);

fclose(input);
fclose(output);

return 0;
}

关于优先级,参看链接:http://www.slyar.com/blog/c-operator-priority.html

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: