gpt4 book ai didi

c# - StreamReader.Read 返回\0

转载 作者:行者123 更新时间:2023-12-01 20:03:32 24 4
gpt4 key购买 nike

我是编码新手。我试图一次从文件中读取几个字符,我的代码如下所示。但是,当文件少于请求的字符时,它会将\0 返回到数组中,\0 是什么意思。请帮我理解。

using (StreamReader sr = new StreamReader(m_segmentFile.TempFileName))
using (StreamWriter sw = new StreamWriter(m_segmentFile.DisplayFile))
{
while ( sr.Peek() >= 0 || m_segmentFile.ParserStatus == ParserStatus.Stopped)
{
buffer = new char[m_segmentFile.FieldWidth];
sr.Read(buffer, 0, buffer.Length);
block = new string(buffer);
if (block[0] != '%')
{
noerrors = m_segmentFile.CheckBlockValidity(block) && noerrors;
int percentComplete = (int)Math.Round((double)(offset * 100) / sr.BaseStream.Length);
if (percentComplete > m_percentParsed && percentComplete <= 100)
{
m_percentParsed = (int)percentComplete;
m_segmentFile.PercentParsed = m_percentParsed;
}
block = (m_segmentFile.FieldWidth * index).ToString() + ":" +block;
sw.WriteLine(block);
index++;
m_parserStatus = ParserStatus.Parsing;
}
else
{
sw.WriteLine(block);
//sr.BaseStream.Seek();
}
}

最佳答案

0 表示文件结束。

来自StreamReader.Read Method (Char[], Int32, Int32)文档:

Return Value
Type: System.Int32
The number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the count parameter, depending on whether the data is available within the stream.

从文件中读取字符的更正确方法是仅使用刚刚使用 String Constructor (Char[], Int32, Int32) 从文件中读取的字符。 。这应该会从字符串中删除多余的 0 字符,并防止您从之前读取的 buffer 中重新读取字符。

int readLength = sr.Read(buffer, 0, buffer.Length);
block = new string(buffer, 0, readLength);

更好的选择可能是使用 StringReader包装您的 StreamReader

关于c# - StreamReader.Read 返回\0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com