Linux 使用 fwrite() 在 C 中逐字节写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13002367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write a file byte by byte in C using fwrite()
提问by PoweredByOrange
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
是一个字符指针。
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.
然而这行不通。我在循环中的第一次迭代中收到分段错误(核心转储)错误。我很确定我的 fwrite() 语句有问题。任何帮助,将不胜感激。
采纳答案by dasblinkenlight
You should pass the addressof curr_char
, not the curr_char
itself:
你应该通过地址的curr_char
,而不是curr_char
本身:
fwrite(&curr_char, 1, sizeof(curr_char), file_to_write);
// ^------ Here
回答by Daniel Fischer
curr_char
is a char pointer.
curr_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.
是错的。您将int
返回的 by隐式转换fgetc
为 a char*
,然后 in fwrite
,该值被解释为一个地址,sizeof(char*)
尝试从中读取字节并将其写入文件。
If curr_char
points to memory allocated for a char
,
如果curr_char
指向为 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
会更接近正确性。但是由于某种原因fgetc
返回 anint
而不是 a char
,它可能会失败,在这种情况下它返回EOF
。所以你应该有
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.
对文件读取错误做出反应。