学习一种比较简便的打印文本数据的方式。
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc,char* argv[])
{
FILE* file1; //定义文件指针
string datapath = "F:\\dyq_work_file\\study_ex\\C++_ex\\FILE_IO\\data"; //定义主文件夹路径
//注意文件夹路径中的反斜杠要打两个,因为打印操作单个反斜杠是默认一种操作模式如 \n和\t这种。
const string file = "\\ test.txt";//文件名
string filename = datapath + file;
const char* filepath = filename.c_str(); //字符串转字符
file1 = fopen(filepath, "w+");//以写的方式创建并打开文件
ofstream(filepath).close(); //关闭
fprintf(file1, " 大家好\n "); //打印
return 0;
}
如果直接进行编译,会提示错误
错误 C4996 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. file_io F:\dyq_work_file\study_ex\C++_ex\FILE_IO\source\main.cpp 16
大致意思就是说fopen不安全啥的,让我们使用fopen_s代替,或者如果要消除这个错误的话,使用_CRT_SECURE_NO_WARNINGS这个,但是不懂怎么使用。于是参考了error C4996: ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead. 报错这篇博客。
方法如下:
1.右键解决方案file_io,然后选择最下面的属性
然后找到C/C++的预处理器中的预处理器定义,把错误提示的_CRT_SECURE_NO_WARNINGS
加到后面,点击应用,确定,即可编译成功。
注意添加的时候别忘了要添加分号
结果: