ofstream not working on linux

丶灬走出姿态 提交于 2020-01-04 03:27:08

问题


i have a simple test code:

#include <string>
#include <iostream>
#include <fstream>

int main() {
std::ofstream strm = std::ofstream("test.txt");
strm << "TEST123";
strm.close();
return 0;
}

if i compile this on windows it works perfectly. however when i compile it on debian with the following command: g++-4.7 -std=c++0x -lpthread TestStream.cpp -ldl -o TestStream than it gives the following output:

i have googled this error to no avail. does anybody know how to fix this? i use a lot of ofstreams in my projects and would like to compile it on linux also.

EDIT: so i have it compiling now thanks to WinterMute however now it prints empty files. how do i fix this?

EDIT2: dunno why but second time compiling it worked. thx!


回答1:


Use

std::ofstream strm("test.txt");

This:

std::ofstream strm = std::ofstream("test.txt");

requires a copy constructor that std::ofstream doesn't have or a move constructor that is available only since C++11. GCC 4.7 does not have full support for C++11 yet, and apparently this is one of the missing features.

In the comments, T.C. mentions that moveable streams won't come to gcc until version 5, which is planned to be released this year. This took me by surprise because gcc claimed full C++11 support with version 4.8.1 -- which is true for the compiler, but not for libstdc++. Reality bites.

So it is perhaps worth mentioning that libc++ (a c++ standard library implementation affiliated with clang and llvm) implements moveable streams, and both clang 3.5 and gcc 4.9 (those are the ones I have here and tried) compile the original code if it is used instead of libstdc++.




回答2:


std::ofstream strm = std::ofstream("test.txt");

ofstream doesn't have copy constructor.



来源:https://stackoverflow.com/questions/27878495/ofstream-not-working-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!