C# 语言 文件读写基础操作指南

C#阿木 发布于 2 天前 3 次阅读


C 语言文件读写基础操作指南

在软件开发过程中,文件读写操作是必不可少的。C 作为一种强大的编程语言,提供了丰富的文件操作功能。本文将围绕 C 语言文件读写基础操作,详细介绍文件的基本概念、文件读写方法以及异常处理等内容,旨在帮助开发者更好地掌握文件操作技巧。

文件的基本概念

在 C 中,文件是存储在磁盘上的数据集合。每个文件都有一个唯一的名称和一个存储位置。文件可以分为两种类型:文本文件和二进制文件。

- 文本文件:以文本形式存储数据,如 .txt、.csv、.xml 等。
- 二进制文件:以二进制形式存储数据,如 .exe、.dll、.jpg、.mp3 等。

文件读写方法

1. 使用 `StreamReader` 和 `StreamWriter` 类

`StreamReader` 和 `StreamWriter` 类是 C 中用于读写文本文件的常用类。以下是一个简单的示例:

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = @"C:example.txt";

// 写入文件
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, World!");
}

// 读取文件
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}

2. 使用 `File` 类

`File` 类提供了对文件的基本操作,如创建、删除、复制、移动等。以下是一些常用的 `File` 类方法:

- `File.Create(string path)`:创建一个新文件。
- `File.Delete(string path)`:删除一个文件。
- `File.Copy(string sourceFileName, string destFileName)`:复制一个文件。
- `File.Move(string sourceFileName, string destFileName)`:移动一个文件。

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string sourcePath = @"C:example.txt";
string destPath = @"C:example_copy.txt";

// 创建文件
File.Create(sourcePath);

// 复制文件
File.Copy(sourcePath, destPath);

// 删除文件
File.Delete(destPath);
}
}

3. 使用 `FileStream` 类

`FileStream` 类用于读写二进制文件。以下是一个简单的示例:

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = @"C:example.bin";

// 写入二进制数据
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] data = { 0x01, 0x02, 0x03, 0x04 };
fileStream.Write(data, 0, data.Length);
}

// 读取二进制数据
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[4];
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Bytes read: " + bytesRead);
for (int i = 0; i < bytesRead; i++)
{
Console.WriteLine("Byte " + i + ": " + buffer[i]);
}
}
}
}

异常处理

在文件操作过程中,可能会遇到各种异常,如 `FileNotFoundException`、`IOException` 等。为了确保程序的健壮性,我们需要对异常进行处理。

以下是一个简单的异常处理示例:

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = @"C:example.txt";

try
{
// 尝试读取文件
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("文件未找到: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("文件操作错误: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("发生未知错误: " + ex.Message);
}
}
}

总结

本文介绍了 C 语言文件读写基础操作,包括文件的基本概念、文件读写方法以及异常处理等内容。通过学习本文,开发者可以更好地掌握文件操作技巧,为后续的软件开发打下坚实的基础。在实际开发过程中,请根据具体需求选择合适的文件读写方法,并注意异常处理,以确保程序的稳定性和可靠性。