简体   繁体   中英

How to add buffering while using getc and putc

I want to make copy/paste with using c FILE but i need to add read/write buffer too and I am not sure how to add it. Is there any function similar to regular read/write..Code is below.

#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;
}

Here's a reworking of your code (sans some error handling) that reads and writes in 256-byte increments:

#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;
}

The output is eg

$ ./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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM