std :: ofstrean不适用于-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

杰里·科芬(Jerry Coffin)

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

std::bind 不适用于参考?

std :: merge不适用于std :: async

std :: bind不适用于std :: sort

重载的operator <<模板不适用于std :: list,尽管适用于std :: vector

NSKeyedUnarchiver不适用于Swift 3

从 BST 中删除节点不适用于 std::pair

std :: map查找不适用于C ++

lang不适用于std :: experimental :: optional

比率数学不适用于std :: chrono :: duration

用户定义的容器不适用于std :: ranges

javaout typemap不适用于指针的std :: vector

std :: cin适用于少量的行,但不适用于较大的行

指向成员的指针的语法糖适用于数组,但不适用于std :: vector

索引 std::vector<bool> 适用于真值,但不适用于假值

M_PI不适用于gcc --std = c11但适用于--std = gnu11?

std :: for_each和std :: execution :: par_unseq不适用于GCC,但适用于MSVC

模板化链接不适用于-O2,但适用于-O0

Scikit-learn仅适用于python 2,而不适用于python 3

D3强制布局适用于Chrome,但不适用于Firefox

pxd相对cimport适用于language_level 2,但不适用于3

适用于Python 2但不适用于Python 3的Python子进程PIPE

模式内部的按钮不适用于Bootstrap 4,但适用于Bootstrap 3

windows API 不适用于 python3,但适用于 python 2

Vue3 适用于 unpkg 但不适用于 npm + webpack

请求模块不适用于 Python3,但适用于 Python

std::chrono 纳秒计时器适用于 MSVC 但不适用于 GCC

std :: erase和std :: remove组合以删除特定元素不适用于特定示例

角路由不适用于Cloudfront + S3

评级插件不适用于Ionic 3