我是编码的新手。我试图从文件中一次读取几个字符,我的代码如下所示。但是,当文件少于请求的字符时,它会将\ 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 :(得分:4)
值0
表示文件结束。
来自StreamReader.Read Method (Char[], Int32, Int32)
文档:
返回值
类型:System.Int32
已读取的字符数,如果在流的末尾没有读取数据,则为0。该数字将小于或等于count参数,具体取决于数据是否在流中可用。
从文件中读取字符的更正确方法是仅使用String Constructor (Char[], Int32, Int32)
从文件中读取的字符。这应该会从您的字符串中删除额外的0
字符,并且还会阻止您从以前的读取中重新读取buffer
中的字符。
int readLength = sr.Read(buffer, 0, buffer.Length);
block = new string(buffer, 0, readLength);
更好的选择可能是使用StringReader
来换行StreamReader
。
答案 1 :(得分:1)
\ 0是字符串终止控制字符 它表示字符串的结尾 - 或者在您的情况下 - 表示文件的结尾。
答案 2 :(得分:0)
因为看起来你正在解析固定宽度的文件结构,所以你很可能会遇到段对齐问题。如果每次需要保持读数,每个块的长度应为m_segmentFile.FieldWidth
,直到填满缓冲区为止。
using (StreamReader sr = new StreamReader(m_segmentFile.TempFileName))
using (StreamWriter sw = new StreamWriter(m_segmentFile.DisplayFile))
{
//I bet money you meant to use && with != stopped not || with == stopped.
while ( sr.Peek() >= 0 && m_segmentFile.ParserStatus != ParserStatus.Stopped)
{
buffer = new char[m_segmentFile.FieldWidth];
int offset = 0;
//Keeps reading till the buffer is totally full;
while(offset < m_segmentFile.FieldWidth && sr.Peek() >= 0 && m_segmentFile.ParserStatus != ParserStatus.Stopped)
{
offset += sr.Read(buffer, offset, buffer.Length - offset);
}
//Reads in to the offset we got to, in case we ended early due to the stream ending or being signaled to stop.
block = new string(buffer, 0, offset);
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();
}
}