[英]std::ofstrean doesn't work with -O3
下面的代码,简单地
1)从命令行参数获取输入文件名,例如in.txt
2)将文件名附加到“ cdf_”
3)打开一个新名称为cdf_in.txt的文件
4)只需从(每一行中的一个数字)中读取每一行,并将其发送到输出文件。
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, char* argv[])
{
char *ben = argv[1]; // example: in.txt
ifstream fin (ben);
char res[30];
char *o1 = "cdf_";
strcat(res, o1);
strcat(res, ben);
ofstream fout (res, std::ofstream::out); // will be cdf_in.txt
cout << res << endl;
uint64_t num; uint64_t sum = 0;
while (fin >> num) {
fout << num << endl;
}
return 0;
}
通过运行程序而没有任何优化,则程序可以正常运行。 但是,通过指定-O3
,它无法创建输出文件。 为什么???
$ g++ -o cdf cdf.cpp
cdf.cpp: In function ‘int main(int, char**)’:
cdf.cpp:19: warning: deprecated conversion from string constant to ‘char*’
$ ./cdf in.txt
cdf_in.txt
$ ls cdf*
cdf cdf.cpp cdf_in.txt cdf.py
$ cat cdf_in.txt
10
5
3
2
1
$ rm cdf_in.txt
$ g++ -O3 -o cdf cdf.cpp
cdf.cpp: In function ‘int main(int, char**)’:
cdf.cpp:19: warning: deprecated conversion from string constant to ‘char*’
$ ./cdf in.txt
cdf_in.txt
$ ls cdf*
cdf cdf.cpp cdf.py
为什么fout
与-O3
不兼容?
您的strcat(res, o1);
取决于res[0] == '\\0'
,这可能是正确的,但不能保证( res
是未初始化的本地,因此未知/未指定其内容)。
可能是,当您不进行优化时将其初始化为零,但当您不进行优化时则被初始化为零。
您可以通过初始化res
或对要复制到其中的第一项使用strcpy
而不是strcat
进行修复(但这仍然会导致缓冲区溢出问题,因此请参见下文,以寻求更好的选择)。
或者,当然,您可以编写更像C ++而不是C的代码,并使用std::string
代替char数组。
std::string fname("cdf_");
fname += argv[1];
std::ofstream fout(fname.c_str()); // just `fout(fname)` with a C++11 compiler
如果您出于某种原因确实想编写类似C的代码,在这种情况下使用sprintf
可能会更容易:
char res[30];
sprintf(res, "cdf_%35s", argv[1]);
std::ofstream fout(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.