[英]Write a file byte by byte in C using fwrite()
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. 其中
int_file_size
是我想要读取的字节数, arch_file
是我正在读取的文件, curr_char
是一个char指针。
However this doesn't work. 但是这不起作用。 I get Segmentation fault (core dumped) error on the first iteration in the loop.
我在循环的第一次迭代中得到Segmentation fault(core dumped)错误。 I'm pretty sure there is something wrong with my fwrite() statement.
我很确定我的fwrite()语句有问题。 Any help would be appreciated.
任何帮助,将不胜感激。
You should pass the address of curr_char
, not the curr_char
itself: 你应该传递
curr_char
的地址 ,而不是curr_char
本身的地址 :
fwrite(&curr_char, 1, sizeof(curr_char), file_to_write);
// ^------ Here
curr_char
is a char pointer.curr_char
是一个char指针。
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. 您隐式将
fgetc
返回的int
转换为char*
,然后在fwrite
中将该值解释为一个地址,尝试从该地址读取sizeof(char*)
字节并将其写入该文件。
If curr_char
points to memory allocated for a char
, 如果
curr_char
指向为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
. 但是
fgetc
返回一个int
而不是char
因为某个原因,它可能会失败,在这种情况下它会返回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. 对文件读取错误做出反应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.