如何在读取文件时避免atoi
How to avoid atoi when read a file
我在一个文件上写一些信息,尤其是无符号的int。稍后另一个程序去阅读这些信息。问题是第二个程序非常慢。我对它进行了简介,它花了50%的时间来做atoi。
有没有办法在文件上写无符号的int来避免atoi(二进制?串行?)
Ps:我使用mmap读取
编辑:
我看到了你的回应,看起来最好的解决方案是将int的二进制内容放在文件
我会看看strtoul()。与atoi()相比,它还有一个优点,那就是它提供了错误处理。
atoi()仍然比使用字符串流更快。然而,使用字符串流来实现这一点是在C++中实现类型安全和标准化的唯一方法。
要实现类型安全和标准化,同时又比字符串流或atoi()或strtoul()之类的东西更快,最好的方法是使用Boost库的约定。
Boost lexical_cast快速且类型安全。
编辑:2016年7月19日下午2:07
在您的情况下,如果您以二进制模式编写文件,则可以完全跳过此操作。一些真正回归基本的东西,比如。。。
ofstream fout;
fout.open("example.bin", ios::binary | ios::out | ios::trunc);
unsigned int int_out;
for(int i=0; i< someArray.length; ++i) {
int_out = someArray[i];
fout.write((char*)&int_out, sizeof(unsigned int));
}
然后你可以用同样的方式在另一端读到它。但是使用。。。
ifstream fin;
fin.open("example.bin", ios::binary);
unsigned int int_in;
for(int i=0; i< someArray.length; ++i) {
fout.read((char*)&int_in, sizeof(unsigned int));
someArray[i] = int_in;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 想要在读取文件时在类型的char上使用atoi()
- 如何在读取文件时避免atoi