#include <fstream>
#include <iostream>
#include <bitset>
using namespace std;
bool isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= sqrt(num); ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main()
{
int n, m;
cout << "请输入开始结束的区间!";
cin >> n >> m;
ofstream fout;
char filename[10] = "data.dat";
fout.open(filename, ios_base::out | ios_base::binary);
if (fout.fail())
{
cout << "打开文件失败!" << endl;
return 0;
}
for (int i = n; i <= m; ++i)
{
if (isPrime(i)) {
fout.write(reinterpret_cast<const char*>(&i), sizeof(int));
}
}
fout.close();
ifstream fin;
fin.open(filename, ios_base::in | ios_base::binary);
if (fin.fail())
{
cout << "打开文件失败!" << endl;
return 0;
}
int num, count = 0;
while (fin.read(reinterpret_cast<char*>(&num), sizeof(int))) {
std::cout << num << "\t";
++count;
if (count % 10 == 0) {
cout << endl;
}
}
cout << endl;
fin.close();
return 0;
}
c++文件流二进制文件读写操作
于 2023-12-08 15:19:30 首次发布