Code-C++-fstream-输出到文件(待完善)

发布时间 2023-04-10 23:48:34作者: Theseus‘Ship

Code-C++-fstream-输出到文件

#include <fstream>
#include <string>

void exportFile(std::string strFileName, int nVal){
    
    std::string strFilePath = "./" + strFileName;
    std::ofstream osFile(strFilePath.c_str(), std::ios::app | std::ios::out);
    if(!osFile.is_open()) return;
    osFile<<"The value is "<<nVal<<std::endl;
    osFile.close();
    
}
/*
void open(const char* filename,int mode,int access);
参数:
filename:要打开的文件名
mode:要打开文件的方式
access:打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:
ios::app:以追加的方式打开文件
ios::ate:文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary:以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in:文件以输入方式打开(文件数据输入到内存)
ios::out:文件以输出方式打开(内存数据输出到文件)
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc:如果文件存在,把文件长度设为0
可以用“或”把以上属性连接起来,如ios::out|ios::binary
打开文件的属性取值是:
0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件
*/

int main(){
    exportFile("log", 1314);
    return 0;
}