背景:
使用的代码本来用fopen打开文件,从debug改成release模式后,就提示不安全,建议改为fopen_s。
于是一顿面向百度debug,改成fopen_s后一直出现“进程已退出”的情况。
errno_t err;
/*initialize and open output files*/
perf_filename = new char[CHAR_LEN];
sprintf_s(perf_filename,CHAR_LEN, "Alg_%i_Performance_D_%.2f_S_%i_%s.txt",
alg_mode,change_degree,change_speed,problem_instance);
/*for performance*/
if ((err = fopen_s(&log_performance, perf_filename, "a")) == 0) {exit(2); }
问题所在:
fopen和fopen_s返回值不同
fopen:打开文件成功的话返回文件指针(赋值给fp),打开失败则返回 NULL值;
fopen_s:打开文件成功返回0,失败返回非0。
前者是打开失败返回NULL,后者是打开成功返回0。
所以其实是打开文件成功了,只是判定条件写反了,改成这样就好了:
if ((err = fopen_s(&log_performance, perf_filename, "a")) != 0) {exit(2); }