6

我正在尝试逐字节读取文件并将其写入另一个文件。我有这个代码:

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);
  }
}

其中int_file_size是我要读取的字节数,arch_file是我正在读取的文件,并且curr_char是一个 char 指针。

但是,这不起作用。我在循环的第一次迭代中收到分段错误(核心转储)错误。我很确定我的 fwrite() 语句有问题。任何帮助,将不胜感激。

4

2 回答 2

10

您应该传递 的地址curr_char而不是其curr_char本身:

fwrite(&curr_char, 1, sizeof(curr_char), file_to_write);
//     ^------ Here
于 2012-10-21T21:28:18.267 回答
4

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.

于 2012-10-21T21:35:54.223 回答