Read zero-terminated text
Intermediate · C#. The empty brackets on char mean a terminated string, not a general array that consumes all remaining bytes.
Run this example
Prerequisites: the repository's .NET 10 SDK and a checkout of this source. Run from the repository root:
dotnet run --project docs/examples/CStructSharp.Docs.Examples.csproj -c Release -- terminated-text
The runner checks 41 42 00 reads AB and writes back unchanged. Success includes PASS terminated-text.
Try the related browser lesson.
Complete program
The layout, options, input bytes, helper methods, and required types are all included. To adapt it outside the repository, create a .NET 10 console project, add CStructSharp, and replace Program.cs with this complete file. These examples follow the source version; use a matching package when testing a release.
Download the complete C# source.
// Generated from executable documentation examples. Edit the source region, then regenerate.
using System;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Buffers;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CStructSharp;
using CStructSharp.Codecs;
using CStructSharp.Diagnostics;
using CStructSharp.Introspection;
using CStructSharp.Values;
internal static partial class Program
{
public static void Main()
{
TerminatedText();
Console.WriteLine("PASS terminated-text");
}
private static void TerminatedText()
{
var layout = new CStruct("struct label { char text[]; };");
byte[] bytes = [0x41, 0x42, 0];
StructValue label = layout.Parse(bytes.AsSpan(), "label");
Equal("AB", label.Get<string>("text"));
SequenceEqual(bytes, layout.Serialize("label", label));
}
private static void Equal<T>(T expected, T actual)
{
if (!EqualityComparer<T>.Default.Equals(expected, actual))
{
throw new InvalidOperationException($"Expected '{expected}', received '{actual}'.");
}
}
private static void SequenceEqual(byte[] expected, byte[] actual)
{
if (!expected.AsSpan().SequenceEqual(actual))
{
throw new InvalidOperationException(
$"Expected {Convert.ToHexString(expected)}, received {Convert.ToHexString(actual)}.");
}
}
}
Try it and diagnose mistakes
Remove the final zero byte.
Answer: Reading fails because the terminator is missing. Restore it; do not assume the end of input is a terminator. The program contains assertions for its original inputs. When changing an input intentionally, update the expected assertion too; an unchanged assertion is not evidence that the new value is wrong.
Continue with the related guide or choose another recipe.