读取文件
ios::in//打开文件用于输入(默认)
ios::binary//以二进制模式(默认模式是文本模式)打开文件
#include<iostream>
#include<fstream>
#include<vector>
#include<cstring>
using namespace std;
int main()
{
ifstream inFile("info.txt",ios::in);
if(!inFile)
{
cerr << "The file can not be opened.";
exit(EXIT_FAILURE);
}
//第一种读取方式--直接读取,以空格换行
char buff1[1024] = {0};
while(inFile >> buff1)
{
cout<<buff1<<endl;
}
//第二种读取方式--数组方法,逐行读取,可读取空格
//默认以换行字符为终止,但只存在于字符数组中,字符数组大小无法扩展,使用具有局限性
char buff2[1024];
while(inFile.getline(buff2,sizeof(buff2))
{
cout<<buff2<<endl;
}
//第三种读取方式--字符串读取,逐行读取,可读取空格,此时getline(【输入流】,【字符串】,【终止字符(可选)】),比如getline(cin,buff3,'t');遇到t停止
string buff3;
while(getline(inFile,buff3))
{
cout<<buff3<<endl;
}
//第四种读取方式--逐字符读取,可读取空格,但效率较低
char inBuf[MAXSIZE] = { 0 };
length = 0;
while ((inBuf[length] = inFile.get()) != EOF) {
if (length < MAXSIZE && inBuf[length] != '\0'
&& inBuf[length] != '\n') // 如果非换行符和'\0'才存入缓存中
++length;
}
inBuf[length] = '\0'; // 字符串封口
char *dataStr;
dataStr = new char[length + 1](); // 申请动态数组并初始化
strcpy(dataStr, inBuf);
//第五种:读取至vector容器中
string s;
vector<string> v1;
while(getline(inFIle,s))
{
inFile>>s;
v1.push_back(s);
}
for(int i=0;i<v1.size();i++)
{
cout<<v1.at(i)<<endl;
}
inFile.close();
return 0;
}
参考:https://blog.csdn.net/qq_44894692/article/details/103618356
输出文件
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
using namespace std;
int main() {
srand((unsigned int)time(0));
ofstream outFile("data.txt", ios::out);
if (!outFile) {
cerr << "The file can not be opened.";
exit(EXIT_FAILURE);
}
// 取[10, 100000]之间的数,总共有100000 - 10 + 1 = 99991个数
for (int i = 0; i < 10; ++i) {
outFile << to_string(10 + rand() % 99991) << endl;
}
return 0;
}
参考:https://github.com/southernEast/SEU_553/blob/master/2018/2/2.cpp
输出文本的格式控制
#include <iostream>
#include <iomanip>//格式控制的头文件
#include <fstream>
using namespace std;
int main() {
ifstream input("Date.txt", ios::in);
if (!input) {
cerr << "The file can not be opened." << endl;
exit(EXIT_FAILURE);
} // 文件处理操作
int day, month, year;
const char* monthStr[] = {
"", "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
};
while (input >> month) { // 一直读取直到EOF
input.ignore(); // 忽略'/'
input >> day;
input.ignore();
input >> year;
input.ignore();
cout << monthStr[month] << " " << setw(2) // 注意这个要填充字符0
<< setfill('0') << day << "," << year << endl;
}
input.close();
return 0;
}
cout<<settiosflags(ios_base::left)//设置文本向左对齐,默认向右对齐
<<setw(6)<<str//设置文本输出宽度为6
<<resetiosflags(ios_base::left)//取消文本向左对齐的格式
<<setw(10)<<str1<<endl;//设置文本输出宽度为10
参考:https://github.com/southernEast/SEU_553/blob/master/2017/1.cpp