libzip の使用時に問題があります。私はLinuxを使用しており、使用してライブラリをインストールしましたsudo apt-get install libzip2 libzip-dev
(したがって、最新バージョンではありません)。
これが私のコードです:
#include <iostream>
#include <zip.h>
#include <unistd.h>
#include <sys/stat.h>
#define ZIP_ERROR 2
using namespace std;
bool isFilePresent(string const& path)
{
struct stat *buf;
return(stat(path.c_str(), buf)==0);
}
int main(void)
{
struct zip *zip;
struct zip_source *zip_source;
int err(0);
string zipFile("filesZip/zipTest");
string fileToZip("filesToZip/test1");
string fileToZip2("filesToZip/test2");
char tmp[] = "filesZip/zipTest\0";
// Test if the file is present
if(isFilePresent(zipFile))
{
// if(remove(tmp) != 0)
if(remove(zipFile.c_str()) != 0)
{
return ZIP_ERROR;
}
}
// Open a zip archive
zip = zip_open(zipFile.c_str(), ZIP_CREATE, &err);
// if there is an error on the opening
if(err != ZIP_ER_OK)
{
cout << "error when opening" << endl;
return ZIP_ERROR;
}
// If the zip file is not open
if(zip == NULL)
{
zip_close(zip);
cout << "error when zip opens" << endl;
return ZIP_ERROR;
}
// zip_source_file zip a file so that it can be added to the zip
if((zip_source = zip_source_file(zip, fileToZip.c_str(), (off_t)0, (off_t)0))== NULL)
{
zip_close(zip);
zip_source_free(zip_source);
cout << "pb when zipping file1" << endl;
return ZIP_ERROR;
}
// Add the zipped file to the zip
if(zip_add(zip, fileToZip.c_str(), zip_source)==-1)
{
zip_close(zip);
zip_source_free(zip_source);
cout << "pb when adding file1" << endl;
return ZIP_ERROR;
}
// zip_source_file zip a file so that it can be added to the zip
if((zip_source = zip_source_file(zip, fileToZip2.c_str(), (off_t)0, (off_t)0))== NULL)
{
zip_close(zip);
zip_source_free(zip_source);
cout << "pb when zipping file2" << endl;
return ZIP_ERROR;
}
if(zip_add(zip, fileToZip2.c_str(), zip_source)==-1)
{
zip_close(zip);
zip_source_free(zip_source);
cout << "pb when adding file2" << endl;
return ZIP_ERROR;
}
// sleep(180);
// Closing the archive
zip_close(zip);
return 0;
}
このコードは、filesToZip フォルダー内の 2 つのファイルを取得し、filesZip フォルダー内の zipTest ファイルに圧縮することになっています。
これを行うには、最初に zipTest ファイルが既に存在するかどうかを確認します。もしそうなら、それはそれを削除します。次に、zip アーカイブを開き、追加するファイルを圧縮してアーカイブに追加してから、アーカイブを閉じます。
だから私の問題は:
zip アーカイブ filesZip/zipTest が存在しない場合、問題なく動作します。zip アーカイブ ファイル Zip/zipTest が存在する場合、コア ダンプが発生します。
私がこれまでに試したこと:
- ファイルの名前に文字列を使用していたためだと思いました。char で試しましたが、何も変わりませんでした
- 次に、削除タスクが完了していないため、競合が発生する可能性があると考えました。したがって、各関数呼び出しの後に (秒単位で) sleep(180) を配置します。何も変わらなかった
- また、アーカイブにファイルを 1 つだけ入れようとしました。何も変更しませんでした
- 何が起こっているのかを確認するために gdb を実行しました。zipアーカイブがすでに存在する場合と存在しない場合の両方を試しました。
- アーカイブがまだ存在していなかった場合: 戻り値 0 まですべてがスムーズに進み、プログラムが fileToZip と fileToZip2 を再定義し、別の戻り値 0 を実行してから停止することがわかりました。
- アーカイブが既に存在する場合: 同じことを行いますが、現在の関数の境界が見つからないと言います。(私はここで、gdbにデバッグ情報がなく、それに不満があることを意味することを読みました..)
私の問題は何か分かりますか?