C中的I / O更快 [英] Faster I/O in C

查看:86
本文介绍了C中的I / O更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,需要从控制台获取1000000行输入,如下所示。

I have a problem which will take 1000000 lines of inputs like below from console.

0 1 23 4 5
1 3 5 2 56
12 2 3 33 5
...
...

我使用过scanf,但速度非常慢。无论如何以更快的方式从控制台获取输入?我可以使用read(),但我不确定每行中的字节数,所以我不能读取()来读取'n'字节。
谢谢,
非常有义务

I have used scanf, but it is very very slow. Is there anyway to get the input from console in a faster way? I could use read(), but I am not sure about the no of bytes in each line, so I can not as read() to read 'n' bytes. Thanks, Very obliged

推荐答案

使用fgets(...)来划一条线一时间请注意,您应检查行末尾的'\ n',如果没有,则要么处于EOF,要么需要读取另一个缓冲区的值,并将两者连接在一起。泡沫,冲洗,重复。不要陷入缓冲区溢出。

Use fgets(...) to pull in a line at a time. Note that you should check for the '\n' at the end of the line, and if there is not one, you are either at EOF, or you need to read another buffer's worth, and concatenate the two together. Lather, rinse, repeat. Don't get caught with a buffer overflow.

然后,您可以自己解析内存中的每条逻辑行。我喜欢使用strspn(...)和strcspn(...)这类东西,但你的里程可能会有所不同。

THEN, you can parse each logical line in memory yourself. I like to use strspn(...) and strcspn(...) for this sort of thing, but your mileage may vary.

解析:
定义分隔符字符串。使用strspn()计算与分隔符匹配的非数据字符,并跳过它们。使用strcspn()来计算与分隔符不匹配的数据字符。如果此计数为0,则表示已完成(行中不再有数据)。否则,将那些N个字符复制到一个解析函数,如atoi(...)或sscanf(...)。然后,将指针基址重置为此块的末尾,并重复skip-delims,copy-data,convert-to-numeric过程。

Parsing: Define a delimiters string. Use strspn() to count "non data" chars that match the delimiters, and skip over them. Use strcspn() to count the "data" chars that DO NOT match the delimiters. If this count is 0, you are done (no more data in the line). Otherwise, copy out those N chars to hand to a parsing function such as atoi(...) or sscanf(...). Then, reset your pointer base to the end of this chunk and repeat the skip-delims, copy-data, convert-to-numeric process.

这篇关于C中的I / O更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆