对我的文本文件应用tabify会导致我的文件阅读器出现segfault
Applying tabify to my text file causes my file reader to seg fault
我有一个包含以下文本的文件records.txt
:
John Smith Sales 555-1234
Mary Jones Wages 555-9876
Paul Harris Accts 555-4321
我已经复制了以下代码从 c++ Programming by Mike McGrath到一个文件format.cpp
中读取records.txt
中的数据:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
const int RANGE = 12;
string tab[RANGE];
int i = 0, j = 0;
ifstream reader("records.txt");
if (!reader)
{
cout << "Error opening input file" << endl;
return -1;
}
while (!reader.eof())
{
if ((i + 1) % 4 == 0)
getline(reader, tab[i++], 'n');
else
getline(reader, tab[i++], 't');
}
reader.close();
i = 0;
while (i < RANGE)
{
cout << endl << "Record Number: " << ++j << endl;
cout << "Forename: " << tab[i++] << endl;
cout << "Surname: " << tab[i++] << endl;
cout << "Daprtment: " << tab[i++] << endl;
cout << "Telephone: " << tab[i++] << endl;
}
return 0;
}
现在,在我的.emacs
文件中,根据以下命令,我将所有文件中的制表符自动转换为空格:
(setq-default indent-tabs-mode nil)
因此,当我编译并运行format.out
时,我得到以下输出:
$ ./format.out
Record Number: 1
Forename: John Smith Sales 555-1234
Mary Jones Wages 555-9876
Paul Harris Accts 555-4321
Surname:
Daprtment:
Telephone:
Record Number: 2
Forename:
Surname:
Daprtment:
Telephone:
Record Number: 3
Forename:
Surname:
Daprtment:
Telephone:
这不是我想要的。我想要的是每个制表符分隔的项目打印在其相应的标签之后。所以我进入emacs
并输入以下命令将records.txt
中的空格转换为制表符:
M-x tabify
但是现在当我重新运行我的脚本,我得到一个segfault:
$ ./format.out
Segmentation fault (core dumped)
为什么会这样,我能做些什么来解决它?(或者,如果原因不明显,我可以做些什么来进一步调查?)
我的c++
代码似乎有问题,而不是文件本身,因为当我在python
中读取records.txt
时,我可以看到它如预期的那样:
In [1]: with open('records.txt') as f:
...: x = f.readlines()
...:
In [2]: x
Out[2]:
['JohntSmithtSalest555-1234n',
'MarytJonestWagest555-9876n',
'PaultHarristAcctst555-4321n']
您可以从阅读为什么while (!reader.eof())
是错误的,为什么循环条件中的iostream::eof被认为是错误的?看来你复制代码的那本书不是很好。
我希望这是你的segfault的原因,因为不正确的eof检查,你在你的循环中进行了太多的次数,并对你的数组进行了越界访问。您可以通过将数组的大小增加到13来检查这一点。
找一本更好的书(顺便问一下是什么书?)。
下面是读取文件的一种可能的方法(未测试的代码)
for (;;)
{
char delim;
if ((i + 1) % 4 == 0)
delim = 'n';
else
delim = 't';
if (!getline(reader, tab[i++], delim))
break; // eof or some other error
}
相关文章:
- 我的文件无法正常工作,无法从C++文件中读取上下文
- 将内容从第一个文件("constituencies")移动到第二个文件("temp")并在之后重命名时,我的文件被删除
- 为什么URLDownloadToFile()没有下载我的文件
- 使用Cygwin C++时出现未定义的引用错误,为什么我的文件没有链接?
- C++ while 循环没有从我的文件中读取 -1
- 这是我的 .h 文件的一些错误,当我在其中包含我的类模板时,它显示 [错误] 未终止 #ifndef
- 为什么我的".a"文件中的所有符号值都是 0
- 不会在登录名中读取C++我的文件
- 使用 c++ 将我的文件拆分为 128 个字节
- 我的C++文件期望用'while'代替 if。最后,它预计会出现'('
- 为什么当我写入文件时,结构在我的文件中消失了
- 视觉C++为什么我的文件在重新启动程序时被截断?
- 我的文件可以编译,但当我尝试运行它时"no such file or directory"
- 在Ostream上使用std :: endl使我的文件二进制
- 无法使用名称空间,也不能在我的.h文件中包含标准的C 库
- 为什么我的文件/目录操作在Windows上工作正常,但在Linux上不能
- 我的C文件是从Pro*C生成的吗
- C++11 fgetc 在"r+b"模式下使用时向我的文件输出 0
- Qt Android:如果我写信给"./myfile.txt",我的文件在哪里?
- 我的C++文件中是否有可能的内存泄漏