感謝您關注我的問題。最近,我開始使用 c 檔案,現在我有幾個關于從末尾到中間讀取檔案的問題。
我的任務是從末尾到中間和從頭到中間讀取我的兩個檔案,不使用陣列和字串庫。之后,如果總和為正數,則將其寫入第三個檔案。如果您能閱讀我的代碼并解釋我的錯誤,我將不勝感激。
這是我的代碼如下:
void calculatingSum(const char* fname, const char* fname2, const char* fname3) {
int size1 = returnSize(fname);
int size2 = returnSize(fname2);
int number = 0;
ifstream fin1;
ifstream fin2;
ofstream fout3;
fout3.open(fname3,ios::binary);
if (size2 > size1) {
fin1.open(fname,ios::binary);
fin2.open(fname2, ios::binary);
}
else
{
swap(size1, size2);
fin1.open(fname2, ios::binary);
fin2.open(fname, ios::binary);
}
int posMedian1 = size1 / sizeof(int)/2;
if (size1 % 2 == 1) {
posMedian1 = 2;
}
int posMedian2 = size2 / sizeof(int) / 2;
if (size2 % 2 == 1) {
posMedian2 = 2;
}
fin1.seekg(-1* sizeof(int), ios::end);
fin2.seekg(-1 *sizeof(int),ios::end);
int a, b;
bool flag = false;
while (fin2.tellg() >= posMedian2) {
fin2.read((char*)&a, sizeof(number));
fin2.seekg(-2 * sizeof(int), ios::cur);
if (fin1.tellg() >= posMedian1) {
fin1.read((char*)&b, sizeof(number));
fin1.seekg(-2 * sizeof(int), ios::cur);
}
else {
if (flag == false) {
flag = true;
fin1.seekg(0);
}
if (fin1.tellg() == posMedian1)
break;
fin1.read((char*)&b, sizeof(number));
}int c = a b;
cout << "c" << c << endl;
if (c > 0)
fout3.write((char*)&c, sizeof(number));
fin1.seekg(0);
fin2.seekg(0);
int d, e;
while (fin2.tellg() <= posMedian2) {
fin2.read((char*)&d, sizeof(number));
fin2.seekg(2* sizeof(int), ios::cur);
if (fin1.tellg() <= posMedian1) {
fin1.read((char*)&e, sizeof(number));
fin1.seekg(2* sizeof(int), ios::cur);
}
else {
if (flag == false) {
flag = true;
fin1.seekg(0,ios::end);
}
if (fin1.tellg() == posMedian1)
break;
fin1.read((char*)&e, sizeof(number));
}int f = e d;
cout << "f" << f << endl;
if (f > 0)
fout3.write((char*)&f, sizeof(number));
}
}
fin1.close();
fin2.close();
}
fin2.seekg(-2 * sizeof(int), ios::cur);它的主要目的是從末尾讀取元素,每次查找前一個元素時,但是當我嘗試執行此操作時出現錯誤..
錯誤串列的影像
uj5u.com熱心網友回復:
代替
fin2.seekg(-2 * sizeof(int), ios::cur);
做
fin2.seekg(-2 * static_cast<ifstream::off_type>(sizeof(int)), ios::cur);
其中off_type是流的偏移型別。否則,-2將被強制轉換為size_t,這是 的型別sizeof,并且是無符號的 - 因此負值-2將變成一個非常大的值。
這種從intto 的隱式轉換size_t可以這樣演示:
#include <fstream>
#include <iostream>
int main() {
size_t x = sizeof(int);
std::cout << -2 * x << '\n'; // not what you'd expect
// ... but this does the right thing:
std::cout << -2 * static_cast<std::ifstream::off_type>(x) << '\n';
}
可能的輸出:
18446744073709551608
-8
由于您經常執行此操作,因此輔助函式會稍微簡化一下:
template<class T>
T& seekg(T& stream, long steps, size_t obj_size) {
stream.seekg(steps * static_cast<typename T::off_type>(obj_size),
std::ios::cur);
return stream;
}
尋求將只是:
seekg(fin2, -2, sizeof(int));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351592.html
上一篇:C編碼有趣
下一篇:列印檔案前10行的問題
