C语言 如何在C中找到文件指针的当前行位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2533451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:59:09  来源:igfitidea点击:

How to find the current line position of file pointer in C?

cfilepointersfile-iofile-pointer

提问by En_t8

How can I get the current line position of the file pointer?

如何获取文件指针的当前行位置?

回答by codaddict

There is no function that gives you current line. But you can use ftellfunction to get the offset in terms of number of char from the start of the file.

没有功能可以为您提供当前行。但是您可以使用ftell函数从文件开头获取以字符数为单位的偏移量。

回答by Thomas

There is no function to get the current line; you'll have to keep track of it yourself. Something like this:

没有获取当前行的函数;你必须自己跟踪它。像这样的东西:

FILE *file;
int c, line;

file = fopen("myfile.txt", "rt");
line = 0; /* 1 if you want to call the first line number 1 */
while ((c = fgetc(file)) != EOF) {
    if (c == '\n')
        ++line;
    /*
        ... do stuff ...
    */
}

回答by paxdiablo

You need to use ftellto give you the position within the file.

您需要使用ftell为您提供文件中的位置。

If you want the current line, you'll have to count the number of line terminator sequences between the start of the file and the position. The best way to do that is to probably start at the beginnning of the file and simmply read forward until you get to the position, counting the line terminator sequences as you go.

如果您想要当前,则必须计算文件开头和位置之间的行终止符序列的数量。最好的方法可能是从文件的开头开始,然后简单地向前阅读,直到到达该位置,同时计算行终止符序列。

If you want the current line position(I assume you mean which character of the current line you're at), you'll have to count the number of characters between the line terminator sequence immediately preceding the position, and the position itself.

如果您想要当前行位置(我假设您的意思是您所在的当前行的哪个字符),则必须计算紧接在该位置之前的行终止符序列与该位置本身之间的字符数。

The best way to do that (since reading backwards is not as convenient) is to use fseekto back up a chunk at a time from the position, read the chunk into a buffer, then find the last line terminator sequence in the chunk, calculating the difference between that point and the position.

最好的方法(因为向后读取不太方便)是使用fseek从位置一次备份一个块,将块读入缓冲区,然后找到块中的最后一行终止符序列,计算该点和位置之间的差异。