gpt4 book ai didi

c - 如何让 ssize_t 输出复制的字节?

转载 作者:行者123 更新时间:2023-11-30 16:09:54 26 4
gpt4 key购买 nike

当尝试使用 ssize_t 打印从文件 1 复制到文件 2 的字节数时,我似乎无法在终端上显示输出。

#include <stdio.h>
#include <fcntl.h>
#include<conio.h>
#define BUF_SIZE 1024

int main(int argc, char* argv[])
{
int fp, fq;
int size = 0;
ssize_t bytesRead, bytesWritten;

char buffer[BUF_SIZE];

mode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IROTH | S_IXOTH;

fp = open(argv [1], O_RDONLY);
if (fp == -1) {
perror("The source file cannot be opened in read mode");
return 1;
}
fq = open(argv[2], O_WRONLY | O_EXCL | O_CREAT, mode);
if (fq == -1) {
perror("File could not be opened in write mode");
return 2;
}

while((bytesRead = read (fp, &buffer, BUF_SIZE))>0){
bytesWritten = write (fq, &buffer, (ssize_t)bytesRead);
}
size = ftell(fp);
printf("Contents of size %zd copied\n", bytesRead);
close (fp);
close(fq);
return 0;
}

最佳答案

在示例中,bytesRead 包含上次调用 read 时读取的字节数,并且 while 循环的每次迭代都会覆盖现有的字节数。值。

添加另一个变量totalBytesRead,将其初始化为0,并在循环内执行totalBytesRead += bytesRead;。然后 totalBytesRead 将保存读取的字节总数。

话虽这么说,您没有检查 write 中的任何错误,因此该变量将包含读取但未写入的字节(例如,当前,即使写入失败,您的代码也会继续读取。您可以添加另一个变量 totalBytesWritten 也在每次迭代中执行与 totalBytesRead 相同的逻辑,并比较您是否写入了所读的所有内容。

关于c - 如何让 ssize_t 输出复制的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58989725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com