Hi All, im pretty new to c#.

Im trying to use this class from codeproject (http://pastebin.com/ZdVGf0wd) to save a struc to file.

This is my *short& test code (http://pastebin.com/bARaBe7a). I am able to write and read a file as long as it only contains one struc. as soon as i save a second struc in the file I segfault and cant figure out why.
as i said, im new and dont totaly understand all that is happening in codeprojects code.

Could anyone give me some pointers please?

ps. sorry if im breaking any rulz putting links in this post
many thanks
steve

Recommended Answers

All 2 Replies

the links that u posted doesnt open.
may be you can copy paste the code here.
Each struct has a size defined by the datatypes declared in that, i suppose you are trying to write on the same position of the file from the second struct, try to use handle and increase the pointer to the next position when you are trying to write from the second struct.

Hi, yeah i see. my bro must have taken it down
This is StructFile.cs by CodeProjects

public class StructFile
	{
		private object		  _oStruct	    = null;
		private System.Type	  _oType		= null;
		private string		  _File			= null;
		private FileStream	  _fs			= null;

		public StructFile(string szFile, System.Type type)
		{
			_File = szFile;
			_oType = type;
		}

		private void LoadFileStream (FileMode FileMode, FileAccess FileAccess, FileShare FileShare)
		{
			if (_fs == null)
			{
				try
				{
					_fs = new FileStream(_File, FileMode, FileAccess, FileShare);
				}
				catch (Exception ex)
				{
					throw ex;
				}
			}
		}

		public bool EOF				//End of File
		{
			get
			{
				if (_fs != null) 
				{
					if (_fs.Position >= _fs.Length) 
						Close();					
				}

				return _fs == null;
			}
		}

		private byte[] StructToByteArray()
		{
			try
			{
			// This function copys the structure data into a byte[]
			byte[] buffer = new byte[Marshal.SizeOf(_oStruct)];									//Set the buffer ot the correct size
			
			GCHandle h = GCHandle.Alloc(buffer , GCHandleType.Pinned);					//Allocate the buffer to memory and pin it so that GC cannot use the space (Disable GC)
			Marshal.StructureToPtr(_oStruct, h.AddrOfPinnedObject(), false);				// copy the struct into int byte[] mem alloc 
			h.Free();																								//Allow GC to do its job
	
			return buffer;																							// return the byte[] . After all thats why we are here right.
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}


		public bool WriteStructure(object oStruct)
		{
			_oStruct = oStruct;
			try
			{
				byte[] buf = StructToByteArray();

				BinaryWriter bw = new BinaryWriter(_fs);

				bw.Write(buf);

				bw.Close();
				bw = null;

				return true;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		public object GetNextStructureValue()
		{
			byte[] buffer = new byte [Marshal.SizeOf(_oType)];
	
			object oReturn = null;

			try
			{
				if (EOF) return null;

				_fs.Read(buffer, 0, buffer.Length);

				GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
				oReturn = (object)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), _oType);
				handle.Free();

				if (_fs.Position >= _fs.Length) 
					Close();

				return oReturn;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		public void Close()			//Close the file stream
		{
			if (_fs != null)
			{
				_fs.Close();
				_fs = null;
			}
			GC.Collect();
		}

		public void Open(FileMode FileMode, FileAccess FileAccess, FileShare FileShare)
		{
			LoadFileStream(FileMode, FileAccess, FileShare);
		}
	}

This is my test code. program.cs

public struct Data
        {
            public string name;
            public int age;
        }
    
    class Program
    {
        static void Main(string[] args)
        {
            Data newInfo = new Data();

            Console.WriteLine("what is your name?");
            newInfo.name = Console.ReadLine();
            Console.WriteLine("what is your age?");
            newInfo.age = int.Parse(Console.ReadLine());

            // open our file
            StructFile sf = new StructFile("Details.info", typeof(Data));
            sf.Open(System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None);
            
            sf.WriteStructure((object)newInfo);
            sf.Close();
            
            Console.WriteLine("your details:");

            Data readData = new Data();
            StructFile sfRead = new StructFile("Details.info", typeof(Data));
            sfRead.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);

            //while(!sfRead.EOF) { 
            readData = (Data)sfRead.GetNextStructureValue();
            Console.WriteLine("Name: {0}", readData.name);
            Console.WriteLine("Age:  {0}", readData.age.ToString());
            Console.WriteLine("------");
            //}

            Console.WriteLine("Done.");
            Console.ReadLine();
        }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.