How to move to a specific position in the file? Use fseek Example: Copy 5 bytes
ID: 3838596 • Letter: H
Question
How to move to a specific position in the file? Use fseek Example: Copy 5 bytes from the file testl.dat, starting at the tenth byte, and append to the end oftest2.dat: % Create files test1.dat and test2.dat % % Each character uses 8 bits (1 byte) fid1 = fopen(1est 1.dat', 'w+') fwrite(fid1, " ABCDEFGHIJKLMNOPQRSTUVWXYZ'); fid2 = fopen ('test2.dat', 'w^+'); fwrite (fid2, 'Second File'); % Seek to the 10th byte ('j)' read 5 fseek(fid1, 9, bof'); A = fread(fid 1, 5, 'uint delta = > char'); felose(fid 1); % Append to test2 dat fseek (fid2, 0, 'eof); fwrite(fid2, A); fclose(fid2)Explanation / Answer
Seek to 10th byte:
fp = fopen( "test1.dat", "rb");
fseek(fp, 10, SEEK_SET);
Then read:
char *pointer_to_string = (char *) malloc( sizeof(char) * 6 );
fread(pointer_to_string, sizeof(char), 5, fp);
and close the first file:
fclose(fp);
To append simple do:
FILE *fp2 = fopen( "test2.dat", "a+");
fwrite(pointer_to_string, sizeof(char),5,fp2);
You must do this also:
#include <stdio.h>
At the end don't forget to:
free(pointer_to_string);
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.