using System;
using System.IO;
using System.Text;
namespace ConsoleApplication21
{
class data
{
private string city;
private string population;
public void getdata()
{
Console.Write("\nEnter city: ");
city = Console.ReadLine();
Console.Write("\nEnter population: ");
population = Console.ReadLine();
}
public int ret_hash()
{
return (get_hash(city));
}
public int get_hash(string key)
{
int hash;
//If key starts with a small letter
if (key[0] >= 'a')
hash = key[0] - 'a';
else //If key starts with a capital letter
hash = key[0] - 'A';
return hash;
}
public void showdata()
{
Console.WriteLine("\nCity: " + city);
Console.WriteLine("\nPopulation: " + population);
Console.WriteLine();
}
static void Main(string[] args)
{
data obj1 = new data();
char ch = 'y';
int hash, spaces, bsize, recsize;
FileStream fs1 = new FileStream(@".\data1.dat", FileMode.Create, FileAccess.Write);
bsize = 26; //Maximum number of records
recsize = 30; //Size of one record
char c = ' ';
StreamWriter w = new StreamWriter(fs1);
spaces = bsize * recsize;
for (int num = 0; num < spaces; num++)
{
w.Write(c);
}
w.Flush();
//Write records to file
Console.Write("Enter records to store in file: \n");
int offset;
while (ch == 'y' || ch == 'Y')
{
obj1.getdata();
hash = obj1.ret_hash();
offset = recsize * hash;
w.BaseStream.Seek((offset), SeekOrigin.Begin);
char[] city_name = new char[20];
for (int i = 0; i < 20; i++)
{
if (i < obj1.city.Length)
city_name[i] = Char.Parse(obj1.city.Substring(i, 1));
}
w.Write(city_name, 0, 20);
w.Write(obj1.population);
w.Flush();
Console.Write("\nDo you wish to continue (y/n):");
ch = Char.Parse(Console.ReadLine());
}
w.Close();
fs1.Close();
//Search for a record in a file
string key;
do
{
FileStream fs2 = new FileStream(@".\data1.dat", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs2);
Console.Write("\nEnter the name of the city to be searched:");
key = Console.ReadLine();
hash = obj1.get_hash(key);
sr.DiscardBufferedData();
sr.BaseStream.Seek((recsize * hash), SeekOrigin.Begin);
data obj2 = new data();
char[] city_name = new char[20];
sr.Read(city_name, 0, 20);
foreach (char item in city_name)
obj2.city = obj2.city + item;
char[] pop_figure = new char[10];
sr.Read(pop_figure, 0, 10);
foreach (char item in pop_figure)
obj2.population = obj2.population + item;
obj2.showdata();
sr.Close();
fs2.Close();
Console.Write("\nDo you wish to continue (y/n): ");
ch = Char.Parse(Console.ReadLine());
} while ((ch == 'y') || (ch == 'Y'));
}
}
}
No comments:
Post a Comment