Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

c++ - fstream operator >> ()sometime crash

I met a crash when I try to read content from a plain file.

#5 0x0d0bef60 in std::__throw_ios_failure(char const*) () from /usr/lib/libstdc++.so.6
#6 0x0d0c2d38 in std::basic_filebuf<char, std::char_traits<char> >::underflow() () from /usr/lib/libstdc++.so.6
#7 0x0d075454 in std::istream::sentry::sentry(std::istream&, bool) () from /usr/lib/libstdc++.so.6
#8 0x0d077510 in std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char> >(std::basic_istream<char, std::char_traits<char> >&, char&) () from /usr/lib/libstdc++.so.6
#9 0x0fc638dc in GetOpenMode () at /home/nvbldr/workspace/working_dir/BaseServices/Utils/src/Misc_func.cpp:38

The code is below:

#define OPEN_ENABLED_FILE"/var/open_mode"

char isOpenMode = default_mode;
fstream openModeFile;
char buff[2];
memset(buff, 0, 2);
openModeFile.open(OPEN_ENABLED_FILE, ios::in);
if (!openModeFile)
{
    isOpenMode = non_open_mode;
}
else
{
    openModeFile>> buff[0]; // Seems this line crashed. 
    isOpenMode = buff[0] == '1' ? open_mode : non_open_mode; 
    openModeFile.close();
}

I cannot see why, this not always happen. We are doing some stress test for 20 hours, only happned in one stress test. Can anyone help give some advice, thanks.

question from:https://stackoverflow.com/questions/65912205/fstream-operator-sometime-crash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code below should work. The only change was the removal of the index operator.

char default_mode = 'w';
char isOpenMode = default_mode;
std::fstream openModeFile;
char buff[20];
memset(buff, 0, 20);
openModeFile.open("./txt.txt", std::ios::in);
if (!openModeFile)
{
  return 0;
}
else
{
    openModeFile>> buff; // Seems this line crashed. 
    isOpenMode = buff[0] // Not sure what you intended so I left it out
    openModeFile.close();
}
    std::cout << buff;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...