文章

07.C++ IO

07.C++ IO

C 操作文件

C 语言的文件读写操作

头文件:

函数原型:FILE * fopen(const char * path, const char * mode);

  1. path:  操作的文件路径
  2. mode: 模式
模式描述
r打开一个已有的文本文件,允许读取文件。
w打开一个文本文件,允许写入文件。如果文件不存在,则会创建一个新文件。在这里,您的程序会从文件的开头写入内容。如果文件存在,则该会被截断为零长度,重新写入。
a打开一个文本文件,以追加模式写入文件。如果文件不存在,则会创建一个新文件。在这里,您的程序会在已有的文件内容中追加内容。
r+打开一个文本文件,允许读写文件。
w+打开一个文本文件,允许读写文件。如果文件已存在,则文件会被截断为零长度,如果文件不存在,则会创建一个新文件。
a+打开一个文本文件,允许读写文件。如果文件不存在,则会创建一个新文件。读取会从文件的开头开始,写入则只能是追加模式。
  • 文件开关
    1. fopen
    2. fclose
  • 字符操作
    1. fputc
    2. fputs
    3. fgetc
    4. fgets
    5. fscanf
  • 字节操作
    1. fread
    2. fwrite
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//========================================================================
FILE *f = fopen("xxxx\\t.txt","w");
//写入单个字符
fputc('a', f);
fclose(f);


FILE *f = fopen("xxxx\\t.txt","w");
char *txt = "123456";
//写入以 null 结尾的字符数组
fputs(txt, f);
//格式化并输出
fprintf(f,"%s",txt);
fclose(f);

//========================================================================
fgetc(f); //读取一个字符

char buff[255];
FILE *f = fopen("xxxx\\t.txt", "r");
//读取 遇到第一个空格字符停止
fscanf(f, "%s", buff);
printf("1: %s\n", buff);

//最大读取 255-1 个字符
fgets(buff, 255, f);
printf("2: %s\n", buff);
fclose(f);

//二进制 I/O 函数
size_t fread(void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);       
size_t fwrite(const void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);
//1、写入/读取数据缓存区
//2、每个数据项的大小
//3、多少个数据项
//4、流
//如:图片、视频等以二进制操作:
//写入buffer 有 1024个字节
fwrite(buffer,1024,1,f);

C++ 操作文件

文件类型分为两种:

  1. 文本文件 - 文件以文本的ASCII 码形式存储在计算机中
  2. 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们

操作文件的三大类:

数据类型描述
ofstream输出文件流,创建文件并向文件写入信息。写操作
ifstream输入文件流,从文件读取信息。读操作
fstream文件流,且同时具有 ofstream 和 ifstream 两种功能。读写操作
  1. ofstream.open
  2. ofstream.close
  3. ifstream.open
  4. ifstream.close
  5. cin
  6. cout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Char data[100];
// 以写模式打开文件
Ofstream outfile;
outfile.Open ("XXX\\f.txt");
Cout << "输入你的名字: ";
//cin 接收终端的输入
Cin >> data;
// 向文件写入用户输入的数据
Outfile << data << endl;
// 关闭打开的文件
Outfile.Close ();

// 以读模式打开文件
Ifstream infile;
infile.Open ("XXX\\f.txt");

Cout << "读取文件" << endl;
Infile >> data;
Cout << data << endl;

// 关闭
Infile.Close ();

文本文件

文件打开方式

打开方式解释
ios::in为读文件而打开文件
ios::out为写文件而打开文件
ios::ate初始位置:文件尾
ios::app追加方式写文件
ios::trunc如果文件存在先删除,再创建
ios::binary二进制方式

注意: 文件打开方式可以配合使用,利用 | 操作符

例如: 用二进制方式写文件 ios::binary | ios:: out

写文件

写文件步骤如下:

  1. 包含头文件:#include <fstream>
  2. 创建流对象:ofstream ofs;
  3. 打开文件:ofs.open("文件路径",打开方式);
  4. 写数据:ofs << "写入的数据";
  5. 关闭文件 ofs.close();

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <fstream>
void test01()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out);
	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	ofs << "年龄:18" << endl;
	ofs.close();
}
int main() {
	test01();
	return 0;
}

读文件

读文件步骤如下:

  1. 包含头文件:#include <fstream>
  2. 创建流对象:ifstream ifs;
  3. 打开文件并判断文件是否打开成功:ifs.open("文件路径",打开方式);
  4. 读数据:四种方式读取
  5. 关闭文件:ifs.close();

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
void test_read()
{
    ifstream ifs;
    ifs.open("test.txt", ios::in);

    if (!ifs.is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }

    // 读取文件内容
    // 1. 第一种方式: 以空格为分隔符
    // char buf[1024] = {0};
    // while (ifs >> buf)
    // {
    //     cout << "[" << buf << "]" << endl;
    // }

    // 2. 第二种方式: 以换行符为分隔符
    // char buf[1024] = {0};
    // while (ifs.getline(buf, sizeof(buf)))
    // {
    //     cout << buf << endl;
    // }

    // 3. 第三种方式: 以换行符为分隔符
    // std::string buf;
    // while (getline(ifs, buf))
    // {
    //     cout << buf << endl;
    // }

    // 4. 第四种:char
    char c;
    while ((c = ifs.get()) != EOF)
    {
        cout << c;
    }

    // 关闭
    ifs.close();
}

二进制文件

写文件

二进制方式写文件主要利用流对象调用成员函数 write

函数原型 :ostream& write(const char * buffer,int len);

参数解释:字符指针 buffer 指向内存中一段存储空间。len 是读写的字节数

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// #include <iostream>
#include <fstream>
// using namespace std;

class Person
{
public:
    char m_Name[64];
    int m_Age;
};

void test_write()
{
    // 创建文件输出流对象
    std::ofstream ofs;
    // 打开文件
    ofs.open("person.txt", std::ios::out | std::ios::binary);
    // 或者
    // std::ofstream ofs1("person.txt", std::ios::out | std::ios::binary);

    // 写入数据
    Person p = {"张三", 18};
    ofs.write((const char *)&p, sizeof(Person));

    // 关闭文件
    ofs.close();
}

int main()
{
    test_write();
    return 0;
}

读文件

二进制方式读文件主要利用流对象调用成员函数 read

函数原型:istream& read(char *buffer,int len);

参数解释:字符指针 buffer 指向内存中一段存储空间。len 是读写的字节数

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <fstream>
#include <string>
class Person
{
public:
	char m_Name[64];
	int m_Age;
};
void test01()
{
	ifstream ifs("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
	}
	Person p;
	ifs.read((char *)&p, sizeof(p));

	cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}
int main() {
	test01();
	return 0;
}
本文由作者按照 CC BY 4.0 进行授权