C++ 读取和写入文件
C++ 将运行结果写入到文件头文件中需要包含#include < fstream > 。 fstream里面包含ofstream(用于输出)和ifstream(用于输入)的类。然后需要声明一个该类的对象,例如outfile。#include<iostream>#include<cstring>#include<fstream>using namesp
·
C++ 读取和写入文件
头文件中需要包含#include < fstream > 。 fstream里面包含ofstream(用于输出)和ifstream(用于输入)的类。然后需要声明一个该类的对象,例如infile,outfile。
open() 函数是 fstream、ifstream 和 ofstream 对象的一个成员。下面是open()函数的用法格式:
void open(const char *filename, ios::openmode mode);
读取文件
可以使用ifstream创建的对象直接用>>读取,但是这样有局限,例如要输入字符串时,遇到空格就会中止读取。这是可以用getline(对象名,变量名)
下面是一个完整的读取文件代码块:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main() {
string str;
ifstream infile;
infile.open("D:\\readin.txt",ios::in); //输入文件的路径,ios::in可以省略
getline(infile,str); //获取文件中的字符串
cout << str;
infile.close(); //调用close()函数关闭文件
return 0;
}
写入文件
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
int main() {
char* p = new char[100];
ofstream outfile;
outfile.open("D:\\readin.txt", ios::out | ios::app);//输入文件的路径
cout << "Writing to the file" << endl;
cin.getline(p, 100);
outfile << p<< endl;
outfile.close(); //调用close()函数关闭文件
delete[] p;
return 0;
}
在程序运行完之后,你可能会希望自动将输出的结果文件打开。可以使用如下代码,程序结束后即可自动调取打开输出的文件夹查看相关内容。
system("start D:\\readin.txt");
运行结果:
更多推荐
所有评论(0)