У меня есть файл, содержащий такую структуру:
public struct index
{
public string word; //30 bytes
public int pos; //4 bytes
};
Что касается слова, то перед его записью я расширяю его до 30 байт, а затем пишу как есть, потому что знаю, что int32 занимает 4 байта.
Вот код для записи в файл:
for (i = 0; i < ind.word.Length; i++)
{
bword[i] = (byte)idx_array[l].word[i];
}
for (; i < SIZE_WORD; i++) //30
{
bword[i] = 0;
}
bw_idx.Write(bword, 0, SIZE_WORD);
bw_idx.Write(ind.pos);
Код компилируется и работает хорошо, за исключением одного: int32 не записывается. Если я проверю файл с помощью notepad ++, я увижу это, где должно быть int: SOH NULL NULL NULL
Я посмотрел SOH, и предполагается, что это SOH (начало заголовка):
Этот символ используется для обозначения начала заголовка, который может содержать информацию об адресе или маршруте.
Может ли кто-нибудь из вас понять, почему мой int32 не пишет?
код для вас, чтобы попробовать (файл будет сохранен в папке bin отладки проекта):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace test_write
{
class Program
{
struct enreg
{
public string word;
public int pos;
}
const int SIZE_WORD = 30; //30 bytes
const int SIZE_POS = 4; //4 bytes
static byte[] bword = new byte[SIZE_WORD];
static byte[] bpos = new byte[SIZE_POS];
static void Main(string[] args)
{
enreg enr = new enreg();
Console.Write("word : ");
enr.word = Console.ReadLine();
Console.Write("\anumber : ");
enr.pos = int.Parse(Console.ReadLine());
FileStream fs = File.Open("temp", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
int i = 0;
for (i = 0; i < enr.word.Length; i++)
{
bword[i] = (byte)enr.word[i];
}
for (; i < SIZE_WORD; i++)
{
bword[i] = 0;
}
bpos = BitConverter.GetBytes(enr.pos);
bw.Write(bword, 0, SIZE_WORD);
bw.Write(bpos, 0, SIZE_POS);
fs.Close();
}
}
}
FileStream.Write(Int32)
. Вы имеете в видуBinaryWriter.Write(Int32)
? - person Alvin Wong   schedule 08.12.2012