【发布时间】:2023-04-09 14:22:02
【问题描述】:
试图通过在 c 中一次复制 n 个字节来将文件的内容复制到另一个文件。我相信下面的代码可以一次复制一个字节,但我不确定如何使它适用于 n 个字节,尝试制作一个大小为 n 的字符数组并将读/写函数更改为 read(sourceFile , &c, n) 和 @ 987654322@,但缓冲区似乎不是这样工作的。
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <time.h>
void File_Copy(int sourceFile, int destFile, int n){
char c;
while(read(sourceFile , &c, 1) != 0){
write(destFile , &c, 1);
}
}
int main(){
int fd, fd_destination;
fd = open("source_file.txt", O_RDONLY); //opening files to be read/created and written to
fd_destination = open("destination_file.txt", O_RDWR | O_CREAT);
clock_t begin = clock(); //starting clock to time the copying function
File_Copy(fd, fd_destination, 100); //copy function
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; //timing display
return 0;
}
【问题讨论】:
-
read()返回读取的字节数。知道何时要对这些字节做某事很重要。 -
while(read(sourceFile , &c, 1) != 0)->while(read(sourceFile , &c, 1) == 1) -
“但缓冲区似乎不是那样工作”是什么意思。意思是?您的尝试以何种方式失败?
-
您应该查看
read的联机帮助页,在这种情况下,函数返回的值可能小于预期的数字。