Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a file byte by byte in C using fwrite()

Tags:

c

linux

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.

like image 707
PoweredByOrange Avatar asked Oct 21 '12 21:10

PoweredByOrange


People also ask

What does fwrite in c do?

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.

Does fwrite create a file?

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.

Where does fwrite write to?

The fwrite() writes to an open file.


2 Answers

You should pass the address of curr_char, not the curr_char itself:

fwrite(&curr_char, 1, sizeof(curr_char), file_to_write);
//     ^------ Here
like image 156
Sergey Kalinichenko Avatar answered Oct 31 '22 12:10

Sergey Kalinichenko


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.

like image 38
Daniel Fischer Avatar answered Oct 31 '22 11:10

Daniel Fischer