Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as C++ by NguyenVietNamSon ( 6 years ago )
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	// Chỉ để mỗi đối số mod là: ios::out thôi, không được để kèm theo ios::in thì trong tình huống file chưa tồn tại thì nó sẽ không tạo ra file
	fstream f("nhiphan.dat", ios::binary | ios::out);
	
	int n = 10;
	int *a = new int[n];

	for(int i = 0; i < n; i++)
	{
		a[i] = rand() % 100; // random giá trị cho các phần tử trong đoạn từ 1 đến 100
	}

	f.write((char *)a, n * sizeof(int));

	if (f)
            cout << "Ghi file thanh cong\n";
        else
            cout << "Ghi file that bai\n";

	f.close(); // đóng file lại kết thúc luồng đầu tiên

	// Mở lại file nhưng lần này có cả 2 chế độ: ios::out, ios::in là để vừa đọc vừa ghi trên cùng 1 file, nhưng cái này chỉ làm được khi file đã có tồn tại
	f.open("nhiphan.dat", ios::binary | ios::out | ios::in);
	
	// Tiến hành đọc lại file để in mảng ra màn hình
	f.seekg(0, f.end);
	n = f.tellg() / sizeof(int);
	f.seekg(0, f.beg);
	
	cout << "\nMang ban dau la: ";
	for(int i = 0; i < n; i++)
	{
		int x;
		f.read((char *)&x, sizeof(int));
		
		cout << x << " ";
	}
	
	// đi sắp xếp mảng trực tiếp trong file
	f.seekg(0, f.end);
	n = f.tellg() / sizeof(int);
	f.seekg(0, f.beg);

	for(int i = 0; i < n - 1; ++i)
	{
		f.seekg(i * sizeof(int), ios::beg);
		int a;
		f.read((char *)&a, sizeof(int));

		for(int j = i + 1; j < n; ++j)
		{
			f.seekg(j * sizeof(int), ios::beg);
			int b;
			f.read((char *)&b, sizeof(int));

			if(a > b)
			{
				f.seekp(i * sizeof(int), ios::beg);
				f.write((char *)&b, sizeof(int));

				f.seekp(j * sizeof(int), ios::beg);
				f.write((char *)&a, sizeof(int));

				a = b;
			}
		}
	}

	// In lại mảng trong file sau khi đã sắp xếp
	cout << "\nMang sau khi da sap xep trong file: ";
	f.seekg(0, f.end);
	n = f.tellg() / sizeof(int);
	f.seekg(0, f.beg);
	
	for(int i = 0; i < n; i++)
	{
		int x;
		f.read((char *)&x, sizeof(int));
		
		cout << x << " ";
	}

	f.close();

	system("pause");
	return 0;
}

 

Revise this Paste

Your Name: Code Language: