【发布时间】:2012-12-08 15:38:54
【问题描述】:
我有一个包含这样结构的文件:
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 没有被写入。如果我使用记事本++ 检查文件,我会看到 int 应该在哪里:SOH NULL NULL NULL
我查了 SOH,它应该是 SOH(标题开头):
这个字符用来表示标题的开始,它可以 包含地址或路由信息。
你们中的任何人都知道为什么我的 int32 没有写入吗?
代码供您尝试(文件将保存在项目的bin debug文件夹中):
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();
}
}
}
【问题讨论】:
-
我猜你最好使用十六进制编辑器而不是 Notepad++。 Frhed 是一个不错的开源软件。还要检查您是否已正确关闭(或刷新)文件。
-
另外,我没有看到
FileStream.Write(Int32)。你的意思是BinaryWriter.Write(Int32)? -
它关闭得很好,即使我冲洗它也不起作用
-
或许您应该隔离问题并提供一个简短的、自包含的代码让我们重现问题
-
正如我所说,使用十六进制编辑器而不是 Notepad++。
标签: c# file int32 binarywriter