使用fseek的原路返回 [英] Using fseek to backtrack

查看:111
本文介绍了使用fseek的原路返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时使用fseek的回溯字符的fscanf业务的可靠?

Is using fseek to backtrack character fscanf operations reliable?

例如像如果我刚才的fscanf-ED 10个字符,但我想走回头路的10个字符可我只是fseek的(INFILE,-10,SEEK_CUR)?

Like for example if I have just fscanf-ed 10 characters but I would like to backtrack the 10 chars can I just fseek(infile, -10, SEEK_CUR) ?

在大多数情况下它的工作原理,但我似乎有字符^ M的问题。显然fseek的寄存器,它作为一个char,但的fscanf没有注册,因此在我的previous例如含^ M就需要fseek的(INFILE,-11,SEEK_CUR),而不是一个10字符块。 fseek的(INFILE,-10,SEEK_CUR)会使得把它用短1个字符。

For most situations it works but I seem to have problems with the character ^M. Apparently fseek registers it as a char but fscanf doesn't register it, thus in my previous example a 10 char block containing a ^M would require fseek(infile, -11, SEEK_CUR) instead. fseek(infile, -10, SEEK_CUR) would make bring it short by 1 character.

为什么会这样?

编辑:我使用的fopen在文本模式

I was using fopen in text mode

推荐答案

您所看到的文本和二进制文件之间的差异。当一个文件中的文本模式(而fopen的第二个参数没有'B')被打开,标准输入输出库可能(实际上必须)间preT根据操作系统的约定文本文件的文件的内容。例如,在Windows中,符合\\ r \\ n结束,这被翻译成由标准输入输出单\\ N,因为这是C约定。当写入一个文本文件,单个\\ n得到输出\\ r \\ n

You're seeing the difference between a "text" and a "binary" file. When a file is opened in text mode (no 'b' in the fopen second argument), the stdio library may (indeed, must) interpret the contents of the file according to the operating system's conventions for text files. For example, in Windows, a line ends with \r\n, and this gets translated to a single \n by stdio, since that is the C convention. When writing to a text file, a single \n gets output as \r\n.

这使得它更容易编写处理文本文件可移植的C程序。一些细节变得复杂,但是,fseeking就是其中之一。正因为如此,C标准只定义fseek的文本文件,在少数情况下:以最开始,到最后,发展到目前的位置,并已与检索一个FTELL previous位置。换句话说,你不能计算寻求文本文件的位置。或者你可以,但你必须采取的所有特定平台的细节照顾好自己。

This makes it easier to write portable C programs that handle text files. Some details become complicated, however, and fseeking is one of them. Because of this, the C standard only defines fseek in text files in a few cases: to the very beginning, to the very end, to the current position, and to a previous position that has been retrieved with ftell. In other words, you can't compute a location to seek to for text files. Or you can, but you have to take care of the all the platform-specific details yourself.

另外,你可以使用二进制文件,并自己做行结束转换。再次,便携性受到影响。

Alternatively, you can use binary files and do the line-ending transformations yourself. Again, portability suffers.

在你的情况,如果你只是想回去的地方,你上次做fscancf,最简单的将是你FTELL只是FSCANF之前使用。

In your case, if you just want to go back to where you last did fscancf, the easiest would be to use ftell just before you fscanf.

这篇关于使用fseek的原路返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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