如何在使用 getc 和 putc 时添加缓冲

How to add buffering while using getc and putc

我想使用 c FILE 创建 copy/paste,但我也需要添加 read/write 缓冲区,但我不确定如何添加它。有没有类似于常规read/write的功能..代码如下.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
    FILE* fsource, * fdestination;

    printf("enter the name of source file:\n");
    char sourceName[20], destinationName[20];
    strcpy(sourceName, argv[1]);
    strcpy(destinationName, argv[2]);


    fsource = fopen(sourceName, "r");
    if (fsource == NULL)
        printf("read file did not open\n");
    else
        printf("read file opened sucessfully!\n");
    fdestination = fopen(destinationName, "w");
    if (fdestination == NULL)
        printf("write file did not open\n");
    else
        printf("write file opened sucessfully!\n");

    char pen = fgets(fsource);
    while (pen != EOF)
    {
        fputc(pen, fdestination);
        pen = fgets(fsource);
    }


    fclose(fsource);
    fclose(fdestination);
    return 0;
}

这是对您的代码的修改(没有一些错误处理),以 256 字节为增量进行读写:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
  char *sourceName = argv[0];
  char destName[256];
  snprintf(destName, 256, "%s.copy", sourceName);
  printf("Copying %s -> %s\n", sourceName, destName);
  FILE *fsource = fopen(sourceName, "rb");
  FILE *fdest = fopen(destName, "w");
  char buffer[256];
  for (;;) {
    size_t bytesRead = fread(buffer, 1, 256, fsource);
    if (bytesRead == 0) {
      break;
    }
    if (fwrite(buffer, 1, bytesRead, fdest) != bytesRead) {
      printf("Failed to write all bytes!");
      break;
    }
    printf("Wrote %ld bytes, position now %ld\n", bytesRead, ftell(fdest));
  }
  fclose(fsource);
  fclose(fdest);
  return 0;
}

输出例如

$ ./so64481514
Copying ./so64481514 -> ./so64481514.copy
Wrote 256 bytes, position now 256
Wrote 256 bytes, position now 512
Wrote 256 bytes, position now 768
Wrote 256 bytes, position now 1024
[...]
Wrote 168 bytes, position now 12968