如何在读取文件时避免atoi

How to avoid atoi when read a file

本文关键字:atoi 文件 读取      更新时间:2023-10-16

我在一个文件上写一些信息,尤其是无符号的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;
 }