簡體   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