简体   繁体   English

C以二进制模式读取文件并写入输出文件

[英]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. 我创建了一个4000块的文件,块大小为4096字节。 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: 因此,我将以“ rb”模式(storeFile)打开创建的文件,并以“ wb”模式(outputFile)打开输出文件,如下所示:

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. 不幸的是,这段代码导致了一个文件,它不是我写到storeFile的文件。 The files' size is BlockUsed*4096Bytes. 文件大小为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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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