簡體   English   中英

向量返回分割錯誤的Fwrite和Fread

[英]Fwrite and Fread for Vector return Segmentation Fault

我用C ++編寫了用於加密和解密的代碼。 第一個代碼創建矢量輸出,然后使用fwrite將其寫入文件,第二個代碼使用fread從第一個讀取輸出。 這是我的代碼片段:

第一個代碼:

.....
string a;
vector<long long int> c;

cout << "message to be encrypted = ";
cin >> a;   
cout << endl;

cout << "Encrypted message : ";
for (i=0;i<a.size();i++) 
{
    x=(int)a.at(i);
    cout << x << " ";
    c.push_back(powerMod(x,e,n));
}

for (i=0;i<c.size();i++) 
{
    //cout << char(c.at(i));
}
cout << endl;

//Write ciphertext c to a file
FILE * pWrite;
pWrite = fopen ("ciphertext", "w");
fwrite (&c , sizeof(c), 1, pWrite);
fclose (pWrite);

輸出為:

message to be encrypted = test
Encrypted message : 116 101 115 116 

然后第二個代碼:

....
//Read Ciphertext from ciphertext
FILE * pRead2;
pRead2 = fopen ("ciphertext", "r");
fread (&c , sizeof(c), 1, pRead2);
//cout << "ciphertext is " << c << endl;

// Decryption
cout << "Decrypted message : ";
for (i=0;i<c.size();i++) 
{
    cout << powerMod(c.at(i),d,n) << " " ;
}
cout << endl;

但它返回:

Segmentation Fault(Core Dumped)

感謝您的幫助,因為我不知道問題出在哪里,無論是fwrite還是fread。 但是我認為問題出在第二個,當它嘗試讀取密文(它是一個向量)時,因為如果我刪除那幾行,程序運行得很好,但是沒有解密消息。

謝謝。

這是因為您編寫了指向矢量對象實例指針 ,而不是實際的矢量數據。 采用

fwrite (&c[0], sizeof(vector<long long int>::value_type), c.size(), pWrite);

還要記住, sizeof(c)返回向量對象實例的大小,而不是向量中的項目數。

讀取向量時,您也遇到類似的問題。 您必須一個接一個地循環執行,將項目再次推到向量上。


如果您學習使用C ++ I / O流庫和一些不錯的標准算法並使用迭代器 ,那么使用C ++可以執行更簡單的操作。

要將向量寫入文件:

std::ofstream os{"ciphertext", std::ios::out};

std::copy(std::begin(c), std::end(c),
          std::ostream_iterator<long long int>(os));

並從文件中讀取:

std::ifstream is{"ciphertext", std::ios::in};

std::copy(std::istream_iterator<long long int>(is),
          std::istream_iterator<long long int>(),
          std::back_inserter(c));

實際上,有一種甚至更簡單的方法可以將文件讀入向量:

std::ifstream is{"ciphertext", std::ios::in};

std::vector<long long int> c(std::istream_iterator<long long int>(is),
                             std::istream_iterator<long long int>());

這依賴於采用兩個迭代器作為參數的std::vector構造函數。


如果您不想使用文本文件,而是二進制文件,那么很遺憾,您必須手動循環並寫入/讀取數據,即,您必須手動執行std::copy為您執行的操作。

像這樣寫數據:

std::ofstream os{"ciphertext", std::ios::out | std::ios::binary};

for (const auto& value : c)
    os.write(reinterpret_cast<const char*>(&value), sizeof(value));

像這樣閱讀它:

std::ifstream is{"ciphertext", std::ios::in | std::ios::binary};

long long int value:
while (is.read(reinterpret_cast<char*>(&value), sizeof(value)))
    c.push_back(value);

如果您沒有基於 C ++ 11 范圍的for循環 (在上面的寫作示例中使用),請使用常規的經典迭代for循環:

std::vector<long long int>::const_iterator i;
for (i = c.begin(); i != c.end(); ++i)
    os.write(reinterpret_cast<const char*>(&(*i)), sizeof(*i));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM