简体   繁体   English

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

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

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

There is no function that gives you current line. 没有功能可以为您提供当前行。 But you can use ftell function to get the offset in terms of number of char from the start of the file. 但是您可以使用ftell函数从文件的开头获取char数量的偏移量。

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 ...
    */
}

You need to use ftell to 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 fseek to 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从位置一次备份一个块,将块读入缓冲区,然后在块中找到最后一行终止符序列,计算该点与位置之间的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM