私は C でいくつかのファイル操作手法を試していたので、ファイルを入力として受け取り、それを空のファイルにコピーする簡単なプログラムを作成しました。「バイナリ」および「読み取り」モードで fopen() を使用して読み取り対象のファイルを開き、fgetc() を使用してすべてのバイトを 1 つずつ読み取り、「書き込み」および「書き込み」モードで開かれた、書き込みたいファイルにそれらを書き込みました。バイナリモード。コピー操作が終了すると (EOF)、両方のファイルで fclose() を呼び出してプログラムを終了しました。
ここに問題があります。テキスト ファイルの場合はすべて問題なく動作しますが、pdf や jpeg などの別の形式でファイルをコピーしようとすると、セグメンテーション エラーが発生します。コードは非常に短く単純なので、この問題はコードのバグではなく、C でこれらのファイル形式を読み書きする方法を理解していないことが原因であると思われます。
提案やアイデアは大歓迎です。コードに何か問題があると思われる場合は、投稿することもできます。
編集:わかりましたので、おそらくコードを台無しにしました。ここにあります:
#include <stdio.h>
#include <stdlib.h>
#define MAXCHAR 10000000
int main( int argc, char** argv)
{
if( argc != 3)
{
printf( "usage: fileexer1 <read_pathname> <write_pathname>");
exit( 1);
}
FILE* file_read;
FILE* file_write;
int nextChar;
char readBuffer[MAXCHAR];
int valid = 0;
// These hold the path addresses to the files to be read and written
char* read_file_path = argv[1];
char* write_file_path = argv[2];
// The file to be read is opened in 'read' and 'binary' modes
file_read = fopen( read_file_path, "rb");
if( !file_read)
{
perror( "File cannot be opened for reading");
exit( 1);
}
// The file to be written into is opened in 'write' and 'binary' modes
file_write = fopen( write_file_path, "wb");
if( !file_write)
{
perror( "File cannot be opened for writing");
exit( 1);
}
nextChar = fgetc( file_read);
while( nextChar != EOF)
{
readBuffer[valid] = (char) nextChar;
valid++;
nextChar = fgetc( file_read);
}
int i;
for( i = 0; i < valid; i++)
{
fputc( readBuffer[i], file_write);
}
fclose( file_read);
fclose( file_write);
return 0;
}