打开文件
const char* fileName="1.txt";//要打开的文件名,可以使路径名,默认情况下是所建工程下
fstream类派生了两个类ifstream\ofstream
fstream f(fileName,参数二);
参数二有多种形式,这里只看主要用的几种:
ios_base::in//打开文件用于读
ios_base::out//打开文件用于写
ios_base::app//打开文件,用于追加(不覆盖原有文件,默认情况是覆盖)
ios_base::binary//以二进制方式打开文件,默认情况下是文本文件方式
例:
fstream i(fileName,ios_base::in|ios_base::out);//打开文件用于读写(既可读也可写)
ifstream in(fileName,ios_base::binary|ios_base::in);//以二进制方式打开文件用于读
ofstream out(fileName,ios_base::out|ios_base::app);//打开文件用于追加
写入CSV文件
#include <iostream> #include <fstream> int main( int argc, char* argv[] ) { ofstream myfile; myfile.open ("example.csv"); myfile << "This is the first cell in the first column.\n"; myfile << "a,b,c,\n"; myfile << "c,s,v,\n"; myfile << "1,2,3.456\n"; myfile << "semi;colon"; myfile.close(); return 0; }