【发布时间】:2019-02-13 10:26:15
【问题描述】:
我有以下结构:
int main(int argc, char **argv) {
try {
FX3USBConnection fx3USB3Connection = FX3USB3Connection();
fx3USB3Connection.send_text_file();
}
catch (ErrorOpeningLib& e) {
printf("Error opening library\n");
return -1;
}
catch (NoDeviceFound& e) {
printf("No device found\n");
return 0;
}
return 0;
}
在 send_text_files 中,我做的最后一件事是比较两个 txt 文件,如下所示:
printf("Loopback recieved, checking if I received the same that I sended\n");
files_match(out_text_filename, in_text_filename);
printf("Exited without problem");
return; // (actually implicit)
我已经使用了files_match 函数的两个版本,但最后一个是这个Compare two files 的精确副本
bool FX3USB3Connection::files_match(const std::string &p1, const std::string &p2) {
bool files_match;
std::ifstream f1(p1, std::ifstream::binary|std::ifstream::ate);
std::ifstream f2(p2, std::ifstream::binary|std::ifstream::ate);
if (f1.fail() || f2.fail()) {
return false; //file problem
}
if (f1.tellg() != f2.tellg()) {
return false; //size mismatch
}
//seek back to beginning and use std::equal to compare contents
f1.seekg(0, std::ifstream::beg);
f2.seekg(0, std::ifstream::beg);
files_match = std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(f2.rdbuf()));
f1.close();
f2.close();
if (files_match) { printf("Files match\n"); }
else { printf("Files not equal\n"); }
return files_match;
}
有时我得到一个错误,有时我没有。当我收到错误消息时:
Loopback recieved, checking if I received the same that I sended
Files match
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
所以,调用files_match 后的打印没有被打印,所以我猜问题出在函数内。但是,我在 return 语句之前进行了打印,并且打印正确。
PS:我评论了函数files_match,没有问题。
PS1:文件可以有任何类似这个字符:¥
【问题讨论】:
-
使用调试器。
-
不相关,这并不重要,但是将变量命名为与函数相同会造成混淆。只是说。
-
'所以,调用 files_match 后的打印没有被打印,所以我猜问题出在函数内部。'不,这不一定是正确的,因为 I/O 是 缓冲 并且它不会立即出现。如果您希望
printf立即出现,您应该使用fflush(stdout);跟随它。或者只是使用调试器,正如已经建议的那样。 -
^^^^ 或:
printf("Exited without problem\n"); -
换行符经常会导致打印到
stdout刷新,但不能保证,最好的方法是添加fflush(stdout);
标签: c++ file-io segmentation-fault ifstream