1、C++文件操作
- ofstream:写操作
- ifstream: 读操作
- fstream : 读写操作
打开方式 | 解释 |
---|---|
ios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 追加方式写文件 |
ios::trunc | 如果文件存在先删除,再创建 |
ios::binary | 二进制方式 |
1.1、写文件
-
包含头文件
#include <fstream>
-
创建流对象
ofstream ofs;
-
打开文件
ofs.open(“文件路径”,打开方式);
-
写数据
ofs << “写入的数据”;
-
关闭文件
ofs.close();
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ofstream ofs;
ofs.open("D:\\学习资料整理\\C++资料\\test.txt", ios::out|ios::app);
ofs << "C++" << endl;
ofs.close();
}
1.2、读文件
-
包含头文件
#include <fstream>
-
创建流对象
ifstream ifs;
-
打开文件并判断文件是否打开成功
ifs.open(“文件路径”,打开方式);
-
读数据
读取数据
-
关闭文件
ifs.close();
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("D:\\学习资料整理\\C++资料\\test.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
}
// 读取一行数据
string res;
while (getline(ifs, res))
{
cout << res << endl;
}
}
2、C文件操作
文件使用方式 | 含义 | 如果指定的文件不存在 |
---|---|---|
r(只读) | 输入数据,打开一个已存在文本文件 | 出错 |
w(只写) | 输出数据,打开一个文本文件 | 建立一个新文件 |
a(追加) | 向文本文件尾添加数据 | 出错 |
rb(只读) | 输入数据,打开一个2进制文件 | 出错 |
wb(只写) | 输出数据,打开一个2进制文件 | 建立新文件 |
r+(读写) | 读写,文本文件 | 出错 |
w+(读写) | 读写,文本文件 | 建立新文件 |
a+(读写) | 读写,文本文件 | 出错 |
rb+(读写) | 读写,二进制文件 | 出错 |
wb+(读写) | 读写,二进制文件 | 建立新文件 |
ab+(读写) | 读写二进制文件 | 出错 |
C++不支持fopen等函数,改用fopen_s等,如果想改变的话:
右键工程名–>属性–>C/C++–>预处理器–>预处理器定义,编辑右边输入框加入:
_CRT_SECURE_NO_WARNINGS
2.1、写文件
2.1.1、fputs
#include<iostream>
#include<string>
using namespace std;
int main()
{
FILE* file;
string str = "python\n";
// 在C++中,fopen已经不能使用
// a+表示追加读写方式
// fopen_s函数如果打开文件成功的话,返回0
if (fopen_s(&file, "D:\\学习资料整理\\C++资料\\test.txt", "a+") != 0)
{
cout << "文件打开失败" << endl;
}
// 将string转为char*
fputs(str.c_str(), file);
fclose(file);
}
2.1.2、fprintf_s
名称 | 引用方式 |
---|---|
fprintf_s | fprintf_s(文件指针,格式字符串) |
#include<iostream>
#include<string>
using namespace std;
int main()
{
FILE* file;
if (fopen_s(&file, "D:\\学习资料整理\\C++资料\\test.txt", "a+") != 0)
{
cout << "文件打开失败" << endl;
}
string str = "C++\n";
fprintf_s(file, str.c_str());
return 0;
}
2.2、读文件
2.2.1、fgets
逐行读取文件
#include<iostream>
#include<string>
using namespace std;
int main()
{
FILE* file;
fopen_s(&file,"D:\\学习资料整理\\C++资料\\test.txt", "r+");
if (file == NULL)
{
cout << "文件不存在" << endl;
return 0;
}
while (!feof(file))
{
char content[100];
// 注意这里,使用fgets时,最后一行也会检查,返回NULL
// 如果不判断的话,最后一行还会输出一次
if (fgets(content, 100, file) == NULL)
break;
cout << content << endl;
}
}
2.2.2、fscanf
#include<iostream>
#include<string>
using namespace std;
int main()
{
FILE* file;
if (fopen_s(&file, "D:\\学习资料整理\\C++资料\\test.txt", "a+") != 0)
{
cout << "文件打开失败" << endl;
}
char str1[100];
char str2[100];
int num;
// 将文件指针移到文件头
rewind(file);
int counter = fscanf(file, "%s %s %d", str1, str2, &num);
cout << str1 << " " << str2 << " " << num;
}