代码之家  ›  专栏  ›  技术社区  ›  SmartestVEGA

文件流文件尾的字符是什么?

  •  13
  • SmartestVEGA  · 技术社区  · 15 年前

    我正在while循环中搜索特定字符,以检查它是否到达文件末尾。

    我能找到哪个角色??

    如:

    Indexof('/n')  end of line
    Indexof(' ') end of word
    ???? ---------- end of file??
    
    7 回复  |  直到 11 年前
        1
  •  16
  •   Mitch Wheat    15 年前

    当流到达流的结尾时。读取返回零。

    MSDN的一个例子, FileStream :

    // Open a stream and read it back.
    using (FileStream fs = File.OpenRead(path))
    {
        byte[] b = new byte[1024];
        UTF8Encoding temp = new UTF8Encoding(true);
        while (fs.Read(b,0,b.Length) > 0)
        {
            Console.WriteLine(temp.GetString(b));
        }
    }
    

    或者,

    using (StreamReader sr = File.OpenText(filepath))
    {
         string line;
         while ((line = sr.ReadLine()) != null)
         {
              // Do something with line...
              lineCount++;
         }
    }
    
        2
  •  6
  •   anijhaw    15 年前

    也许你要找的是这个

    using (StreamReader sr = new StreamReader("TestFile.txt"))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
             Console.WriteLine(line);
        }
    }
    
        3
  •  6
  •   erha    12 年前

    当FILESTREAM返回0时,并不意味着您已经到达文件末尾。我有过这样的经历。

    来自MSDN: 读入缓冲区的字节总数。如果请求的字节数为 当前不可用 ,如果到达流的结尾,则为零。

    这种情况发生在诸如thumbdrive之类的慢速设备上。

        4
  •  4
  •   Samuel Neff    11 年前

    没有EOF字符。呼叫 FileStream.Read 在一个循环中什么时候? .Read() 如果未读取字节,则返回0。

    文档对这种行为非常清楚。

    http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx

    read方法仅在到达流的末尾后返回零。否则,read总是在返回之前从流中读取至少一个字节。如果在调用read时流中没有可用的数据,则方法将阻塞,直到至少可以返回一个字节的数据为止。即使没有到达流的末尾,实现也可以返回比请求的字节少的字节。

        5
  •  3
  •   Thomas Levesque    15 年前

    字符串(甚至文件)中没有“文件结尾字符”。字符串的长度是已知的( Length 所以没必要

    读取文件时,可以检查:

    • 如果 Stream.Read 返回0
    • 如果 StreamReader.ReadLine 返回空值
        6
  •  2
  •   Mattias S    15 年前

    没有这种性格。如果调用filestream.readbyte,它将返回-1作为文件结尾。read方法返回读取的零字节。如果在流周围使用streamreader,则其readline方法返回null或其endofstream属性返回true。

        7
  •  -1
  •   ItsAllABadJoke    11 年前

    有时候你不想读整行。例如,如果行很长,或者将字符串保存在临时变量中没有用处。

    在这些情况下,可以使用 PEEK() 在上的函数 流读出器 . 当它返回-1时,你就结束了。例如:

        // Reads a CSV file and prints it out line by line
        public static void ReadAndPrintCSV(string fullyQualifiedPath)
        {
            using (System.IO.StreamReader sr = File.OpenText(fullyQualifiedPath))
            {
                string[] lineArray = null;
                while ((sr.Peek() > -1) && (lineArray = sr.ReadLine().Split(',')) != null)
                {
                    foreach (string str in lineArray)
                    {
                        Console.Write(str + " ");
                    }
                    Console.WriteLine();
                }
            }
        }