Reputation: 648
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!
Upvotes: 0
Views: 342
Reputation: 2857
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
Upvotes: 0
Reputation: 121659
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;
}
Upvotes: 0