I'm trying to read a file byte by byte and write it to another file. I have this code:
if((file_to_write = fopen(file_to_read, "ab+")) != NULL){
for(i=0; i<int_file_size; i++){
curr_char = fgetc(arch_file);
fwrite(curr_char, 1, sizeof(curr_char), file_to_write);
}
}
where int_file_size
is the amount of bytes I want to read, arch_file
is the file I'm reading from, and curr_char
is a char pointer.
However this doesn't work. I get Segmentation fault (core dumped) error on the first iteration in the loop. I'm pretty sure there is something wrong with my fwrite() statement. Any help would be appreciated.
In the C Programming Language, the fwrite function writes nmemb elements (each element is the number of bytes indicated by size) from ptr to the stream pointed to by stream.
The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
The fwrite() writes to an open file.
You should pass the address of curr_char
, not the curr_char
itself:
fwrite(&curr_char, 1, sizeof(curr_char), file_to_write);
// ^------ Here
curr_char
is a char pointer.
In that case,
curr_char = fgetc(arch_file);
is wrong. You're implicitly converting the int
returned by fgetc
to a char*
, and then in fwrite
, that value is interpreted as an address, from which the sizeof(char*)
bytes are tried to be read and written to the file.
If curr_char
points to memory allocated for a char
,
*curr_char = fgetc(arch_file);
fwrite(curr_char, 1, sizeof *curr_char, file_to_write);
would be closer to correctness. But fgetc
returns an int
and not a char
for a reason, it may fail, in which case it returns EOF
. So you should have
int chr = fgetc(arch_file);
if (chr == EOF) {
break; // exit perhaps?
}
char c = chr; // valid character, convert to `char` for writing
fwrite(&c, 1, sizeof c, file_to_write);
to react to file reading errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With