繁体   English   中英

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

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

我创建了一个4000块的文件,块大小为4096字节。 我写入了该文件中的某些特定块,现在我想读取这些块并将结果写入新的输出文件中。

因此,我将以“ rb”模式(storeFile)打开创建的文件,并以“ wb”模式(outputFile)打开输出文件,如下所示:

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

现在我正在尝试寻找正确的位置并将所有块读取到新文件(输出文件):

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

不幸的是,这段代码导致了一个文件,它不是我写到storeFile的文件。 文件大小为BlockUsed * 4096Bytes。

我究竟做错了什么?

先感谢您!

这是一个愚蠢的示例,但可能有助于说明几点:

#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