1

在 C 中,我只想扫描输入中的一些行以节省程序的运行时间。例如:

假设我的输入文件包含一些随机数,例如:

5 1
1 2
1 7
5 6
3 4
1 6
2 5 3
1 5 4
3 1 1

在这里,我想跳过所有双打数字并从三倍数字开始,即

2 5 3
1 5 4
3 1 1

我可以重定向 scanf() 以便它从中间的某个地方开始扫描吗?

4

2 回答 2

2

您可以使用该fseek函数将文件光标跳转到文件中的任意偏移量,前提是您知道需要跳过的字节数。

如果您事先不知道需要跳过多少个字符,最好的选择是不断地从文件中读取行并跳过那些不符合您的条件的行。在你的情况下,你可以跳过所有只有一个空格字符的行,一旦你找到一行有两个空格就可以继续阅读。

希望这可以帮助!

于 2013-02-07T23:02:22.947 回答
2

You can read and ignore data until you reach what you want. For example, read a line with fgets, then use sscanf to try to convert that line to three numbers. If the return from sscanf isn't 3, it couldn't convert three numbers, so continue to the next line. When sscanf does return 3, then you can save the results in an array (or whatever).

To truly skip to a later point in the file, you'd need to know the offset to skip to, and feed that to fseek. That seems unlikely to apply here though.

If your file is large and you know (for sure) that it consists solely of 2-number lines followed by 3-number lines, you could do something like a binary search to find the first 3-number line. You'd start by finding the file length, then seek (about) halfway into the file. Read and ignore one line (because you probably didn't seek to the beginning of a line). Then read the next line and try to convert it as above. If it has three numbers, then you're past the point that the three-number lines started, so try again about halfway back to the beginning (and if it's only a 2-number line, halfway further to the end).

You probably don't want to keep this up too long -- when you're within a few kilobytes (or so) of the beginning of the three-number lines, it's probably faster to just read sequentially until you find the beginning instead of doing a lot more seeking to find exactly the right point.

于 2013-02-07T23:03:05.007 回答