私はC + +の宿題を持っています。宿題はcプログラムをc ++に変換するよう求めています。 以下は質問です。
次のC関数をC ++に変換するように要求されています
それを完全なプログラムに埋め込んでテストします。注意
この関数はテキストではなく整数のバイナリファイルをコピーする
ファイル。プログラムは引数を受け入れる必要があります(コピーするファイルと
コピーするファイル)をコマンドラインから削除します。
/* ==================== cpyFile =====================
This function copies the contents of a binary file
of integers to a second file.
Pre fp1 is file pointer to open read file
fp2 is file pointer to open write file
Post file copied
Return 1 is successful or zero if error
*/
int cpyFile (FILE *fp1, FILE *fp2)
{
/* Local Definitions */
int data;
/* Statements */
fseek (fp1, 0, SEEK_END);
if (!ftell (fp1))
{
printf ("nacpyFile Error : file emptynn");
return 0;
} /* if open error */
if (fseek (fp1, 0, SEEK_SET))
return 0;
if (fseek (fp2, 0, SEEK_SET))
return 0;
while (fread (&data, sizeof (int), 1, fp1))
fwrite (&data, sizeof (int), 1, fp2);
return 1;
} /* cpyFile */
私は最善を尽くし、それを変換することができましたが、残念なことに私がそれを使用しているときに、コピーの後に得たファイルは空です。以下は私の答えです:
#include
#include
#include
using namespace std;
int main(int argc,char* argv[])
{
if(argc!=3)
{cerr<<"invalid number of arguments. must be 3."<<<<" could not be opened"<<<"file could not be found."<<<"nacpyFile Error : file emptynn";
return 0;
} /* if open error */
if (fp1.seekg (0, ios::beg))
return 0;
if (fp2.seekg (0, ios::beg))
return 0;
while (fp1.read (reinterpret_cast(&data), sizeof (int)))
{
fp2.seekp(0);
fp2.write (reinterpret_cast(&data), sizeof (int));
}
return 1;
}
私はベストを尽くし、すべてが正常に動作していることを除いて、バイナリファイルをコピーすると、私が得るファイルは空であり、理由は分かりません。
バイナリモードでファイルを開く必要があります。
fstream fp1(argv[1], ios::in | ios::binary);//combine ios::in with ios::binary
fstream fp2(argv[2], ios::out | ios::binary);//combine ios::out with ios::binary
または、 ifstream
(読み込み専用のファイルストリーム)と
ofstream
(ファイルストリーム ifos
は
iOS :: in
を意味するため、
iOS :: in
と iOS :: out
ofstream
は
iOS :: out
を意味します:
ifstream fp1(argv[1], ios::binary);
ofstream fp2(argv[2], ios::binary);
これを行う必要があるのは、ファイルを読み書きするときに r n
や
だけを
r n
などに置き換えて、バイナリデータを混乱させます。
この:
if (fp1.seekg (0, ios::beg))
return 0;
if (fp2.seekg (0, ios::beg))
return 0;
Will always make your code return because seekg
returns the object you call it on. It’s not the equivalent of
fseek
in this regard because fseek
returns 0 on success. So you never get to the while
loop. Take those out of the if
statements so that it
looks like この:
fp1.seekg(0, ios::beg);
fp2.seekg(0, ios::beg);
または、チェックをしなければならない場合は、実行したい
if (!fp1.seekg (0, ios::beg))//notice the added !
return 0;
if (!fp2.seekg (0, ios::beg))//notice the added !
return 0;
また、これ( while
内):
fp2.seekp(0);
書き込むポイントをファイルの先頭に設定しています。だから、ファイルの始めに何も書いてはいけません。その行を完全に削除してください。
Also, you have a Nevermind that, misread due to the unusual bracereturn
inside the loop
which makes it return on the first iteration. Move the return
outside the loop so you only return after the loop is
1;
finished.
style.