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

标签 c

当尝试使用 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/

相关文章:

linux - 问题

c - 一元 '*' 的无效类型参数(有 int?

c - 十进制到十六进制转换 (C) 不适用于大数

c - 使用 system tap 时如何避免 "probe overhead exceeded threshold"错误?

c - 如何阻止 GCC 将此逐字节复制优化为 memcpy 调用?

c - 无法理解 void (*fptr)(void) 指针在 void 数组中的使用

c - 如何在结构体中将 char[] 分配给 null

c - 下面的数组初始化方法与数组边界检查的上下文有何不同?

python - 将 c 结构体返回给 python 时出错

c - 删除链表的唯一节点