私はワードファイル(.doc)を使用しなければならないファイルシステムのIOコードを使用してファイルを半分に分割し、バイナリモードのファイル。私は以下のコードを書いて、正常に実行して2つのファイルを生成します。ファイルのサイズが元のファイルの半分であっても。しかし、私が単語ファイルを開くために行くとき、彼らは壊れて出てくる。これは.txtファイルでうまく動作しますが、インストラクターはファイルの破損がない.docファイルと.zipファイルで動作するはずだと言いました。私のコードに何か問題がありますか?助けてくれてありがとう、本当に感謝しています。Cでバイナリファイルを破損せずに分割する
#include <stdio.h>
int main (int argc, char **argv)
{
char *fileName = "1.doc";
char *buffer = "a";
int chunk;
FILE *fd;
fd = fopen (fileName, "rb");
if (fd == NULL);
ferror ("error");
fseek (fd, 0, SEEK_END);
chunk = ftell (fd)/2;
rewind (fd); //open file, get size, set chunk = to half the file, rewind back to begining of file
fread (buffer, chunk, 1, fd);
fclose (fd); //read the first half of the file into buffer
fd = fopen ("1_1.doc", "wb");
fwrite (buffer, chunk, 1, fd);
fclose (fd); //create new file, write the contents of buffer into it
fd = fopen (fileName, "rb");
fseek (fd, chunk, SEEK_SET);
fread (buffer, chunk, 1, fd);
fclose (fd); //reopen original file, go to half the file, read the remaining half of the file and store in buffer
fd = fopen ("1_2.doc", "wb");
fwrite (buffer, chunk, 1, fd);
fclose (fd); //create a new file, write the second half of the file into it
return 0;
}
は、私はあなたが、平均して、半分のバイトを失ってしまった
fwrite(buffer, chunk, 1, fd);
と
fwrite(&buffer, chunk, 1, fd);
'fd = NULL'の場合はどうなりますか? (ヒント - 終了しません)。どのくらいのメモリが 'buffer'に割り当てられていますか? –
私はあなたがバッファのためのメモリを割り当てているとは思わない - したがって、未定義の振る舞い – John3136
'doc'と' zip'ファイルは内部構造を持っています。ファイルを半分に分割するだけでファイルが破損し、ファイルを使用できなくなります。おそらくあなたはあなたのインストラクターを誤解したでしょう。 – Ari0nhh