下面的代码,简单地
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句