c++ - 如何使用读取系统调用写入文件?以及如何确定缓冲区大小?
问题描述
我正在编写一个从文件读取并写入另一个文件的代码,我在决定放置缓冲区大小时遇到问题,因为我不知道,它可能是任何文件,以及如何从文件中读取使用while循环?:
在这里我打开了第一个文件:
int fd1 = open(args[1], O_RDONLY);
if(fd1 == -1){
perror("error");
return;
}
在这里我打开了第二个文件:
int fd2 = open(args[2], O_WRONLY|O_TRUNC);
if (fd2 == -1) { // if we couldn't open the file then create a new one (not sure if we supposed to this ?)
fd2 = open(args[2], O_WRONLY|O_CREAT, 0666);
if (fd2 == -1) {
perror("error");
return;
}
}
这就是我试图阅读的方式:
char* buff;
int count = read(fd1, buff, 1); /// read from the file fd1 into fd2
while (count != -1) {
if (!count) {
break;
}
if (write(fd2, buff, 1) == -1) {
perror("smash error: write failed");
return;
}
read_res = read(fd1, buff, 1);
if (read_res == -1) {
perror("smash error: read failed");
return;
}
}
cout <<"file1 was coppiesd to file 2" << endl ;
解决方案
你应该阅读指针。读取函数需要一个要使用的指针。传统的解决方案看起来像
#SIZE 255
char buff[SIZE]
int count = read(fd1, buff, SIZE)
//add logic to deal reading less then SIZE
这是因为数组的名称是指向数组中第一个元素的指针。
如果您只想一次读取一个字节,我建议按照我在下面所做的操作,将 buff 更改为 char(而不是 ptr 到 char),并简单地将 buff 的地址与 & 一起传递
char buff;
int count = read(fd1, &buff, 1); /// priming read
while (count != -1) {
if (!count) {
break;
}
if (write(fd2, &buff, 1) == -1) {
perror("smash error: write failed");
return;
}
read_res = read(fd1, &buff, 1);
if (read_res == -1) {
perror("smash error: read failed");
return;
}
}
cout <<"file1 was coppiesd to file 2" << endl ;
让我知道这是否不起作用
推荐阅读
- flutter - 按下按钮时 Flutter DraggableScrollableSheet 未显示
- visual-studio-code - editor.wordWrap 在奇怪的位置包装文本
- r - 如何匹配模式不同的三列?
- sql - 具有 NULL 值的简单 1:1 映射表的主键?
- php - 使用 XML-RPC 将图像上传到 Odoo12
- html - 如何在 HTML 中使内部 div 元素可滚动(假设正文不是)?
- vue.js - 单个文件组件 - 在从导航栏更改值时重新安装组件
- java - 页面完全加载后读取页面源代码(执行 JavaScript)
- html - Different height and position for col in bootstrap
- mongodb - 向文档 mongodb 添加字段以保留以前的数据