C++中如何使用Filestream进行文本写入和读取操作?

如题所述

C++示例代码展示了如何使用System.IO命名空间的FileStream类进行文本文件的读写操作。首先,我们定义一个名为AddText的方法,用于将UTF-8编码的字符串写入文件流:



private static void AddText(FileStream fs, String value)
{
byte[] info = (new UTF8Encoding(true)).GetBytes(value);
fs.Write(info, 0, info.Length);
}

在main函数中,我们创建一个名为"MyTest.txt"的文件,如果文件已存在则先删除。然后,创建一个FileStream对象并使用AddText方法写入多行文本,每10个字符后添加换行符:



FileStream fs = File.Create(path);
try
{
AddText(fs, "This is some text");
AddText(fs, "This is some more text,");
AddText(fs, "\r\nand this is on a new line");
// ... (更多文本写入)
for (int i = 1; i < 120; i++)
{
AddText(fs, Convert.ToString((char)i));
if (Math.IEEEremainder(Convert.ToDouble(i), 10) == 0)
{
AddText(fs, "\r\n");
}
}
}
finally
{
fs.Dispose();
}

接着,我们打开文件进行读取,使用UTF-8编码将内容逐行输出到控制台:



FileStream fs = File.OpenRead(path);
try
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
finally
{
fs.Dispose();
}

这段代码展示了如何使用FileStream进行文件操作,包括创建、写入和读取文本内容。



扩展资料

FileStream 类是公开以文件为主的 Stream,既支持同步读写操作,也支持异步读写操作。 命名空间:System.IO 程序集:mscorlib(在 mscorlib.dll 中)

温馨提示:答案为网友推荐,仅供参考