简体   繁体   中英

C reading a File in binarymode and write to an output file

I created a File of 4000 blocks with a blocksize of 4096 Bytes. I wrote to some specific blocks in this file and now I want to read these blocks and write the result into a new output file.

Therefore I open the file I created in "rb" mode (storeFile) and the outputfile in "wb" mode (outputFile) as follows:

FILE * outputFile=fopen(outputFilename,"wb");
FILE * storeFile=fopen(storeFilename, "rb");

now I am trying to seek for the right position and read all blocks to the new file (outputfile):

for(i=0; i<BlocksUsed; i++)
{
    fseek(storeFile,blocksToRead[i]*4096,SEEK_SET);
    fread(ptr, 4096,1,storeFile);
    fwrite(ptr,4096,1outputFile);
    ...
    rewind(storeFile)
 }

unfortunately this code leads to a file which is not the file I wrote to the storeFile. The files' size is BlockUsed*4096Bytes.

What am I doing wrong?

Thank you in advance!

Here's a silly example, but it might help illustrate a few points:

#include <stdio.h>

int
main (int argc, char *argv[])
{
  FILE *fp_in, *fp_out;
  int c;

  /* Check command-line */
  if (argc != 3) {
    printf ("EXAMPLE USAGE: ./mycp <INFILEE> <OUTFILE>\n");
    return 1;
  }

  /* Open files */
  if (!(fp_in = fopen(argv[1], "rb"))) {
    perror("input file open error");
    return 1;
  }

  if (!(fp_out = fopen(argv[2], "wb"))) {
    perror("output file open error");
    return 1;
  }

  /* Copy bytewise */
  while ((c = fgetc(fp_in)) != EOF)
    fputc (c, fp_out);

  /* Close files */
  fclose (fp_out);
  fclose (fp_in);
  return 0;
}
 fseek(storeFile,blocksToRead[i]*4096,SEEK_SET);
 int n = fread(ptr, 4096,1,storeFile);
 if (n <0)
 {printf("read error\n");return -1;}
 if(fwrite(ptr,n,1outputFile) != n)
 {printf("write error\n"); return -1;}
    ...
 //rewind(storeFile)// no need . since you use fseek 

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