C++之文件操作
标准输入流
#define _CRT_SECURE_NO_WARNINGS
#include <iostream> // 标准的输入输出流
using namespace std; // 命名空间 防止命名冲突
#include <cstring>
#include <stdexcept> // 系统异常类
// main 函数
int main()
{
// // 一次只能读取一个字符
// char c = cin.get();
// cout << "1 : " << c << endl;
// // 一次读取一个字符
// cin.get(c);
// cout << "2 : " << c << endl;
// // 一次读取n个字符
// char buff [1024];
// cin.get(buff,1024);
// cout << "3 " << buff << endl;
// // 读取一行
// cin.getline(buff,1024);
// cout << "4 " << buff << endl;
// // 忽略n个字符
// cin.ignore(2);
// char c = cin.get();
// cout << "5 : " << c << endl;
// 偷窥 打印的一样
// char c = cin.peek();
// cout << "6 : " << c << endl;
// c = cin.get();
// cout << "7 : " << c << endl;
// 放回
// char c = cin.get();
// cout << "8 : " << c << endl;
// cin.putback(c);
// char buff [1024];
// cin.getline(buff,1024);
// cout << "9 : " << buff << endl;
// 案例:
// int num;
// cout << "请输入一个1~10的数字" << endl;
// while (1)
// {
// cin >> num;
// if(num <= 10 && num >= 1){
// cout << "输入的数字为 :" << num << endl;
// break;
// }
// cin.clear();
// cin.sync();
// cout << "标志位 :" << cin.fail() << endl; // 0 是正常的 1 是不正常的
// }
system("pause"); // 阻塞功能
return EXIT_SUCCESS; // 正常退出
}
标准输出流
// main 函数
int main()
{
// 输出
cout.put('a').put('b'); //ab
char buff [1024] = "hello world";
cout.write(buff,strlen(buff)); // hello world
// 输出格式
int number = 99;
cout.width(5); // 99
cout.fill('*'); //***99
cout.setf(ios::left); //99***
cout.unsetf(ios::dec);
cout.setf(ios::hex); //63*** //十六进制
cout.setf(ios::showbase);//0x63* //强制输入整数基数0 0x
cout.unsetf(ios::hex);
cout.setf(ios::oct); //0143* //八进制
cout << number << endl;
system("pause"); // 阻塞功能
return EXIT_SUCCESS; // 正常退出
}
文件读写操作
#define _CRT_SECURE_NO_WARNINGS
#include <iostream> // 标准的输入输出流
using namespace std; // 命名空间 防止命名冲突
#include <cstring>
#include <stdexcept> // 系统异常类
#include <fstream>
void write_to_file(){
ofstream ofs;
// 打开文件 写入文件 如果有,则清空再写入,如果没有则创建
ofs.open("./test/world.txt",ios::out|ios::trunc);
// 是否打开成功
if(!ofs.is_open()){
cout << "打开文件失败" << endl;
return;
};
ofs << "hello" << endl;
ofs << "world" << endl;
cout << "写入文件成功" << endl;
}
void read_to_file(){
// 读取文件
ifstream ifs("./test/hello.txt",ios::in);
if(!ifs.is_open()){
cout << "文件打开失败" << endl;
return;
}
// 方式一:
// char buff [1024];
// while (ifs>>buff)
// {
// cout << buff << endl;
// }
// // 方式二:
// char buff [1024];
// while (!ifs.eof())
// {
// ifs.getline(buff,sizeof(buff));
// cout << buff << endl;
// }
// 方式三:不推荐
// char ch;
// while((ch = ifs.get()) != EOF){
// cout << ch << endl;
// }
}
// main 函数
int main()
{
// write_to_file();
// read_to_file();
system("pause"); // 阻塞功能
return EXIT_SUCCESS; // 正常退出
}