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

发布于 2024-08-26 16:42:34 字数 22 浏览 5 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

昇り龍 2024-09-02 16:42:34

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

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.

画▽骨i 2024-09-02 16:42:34

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

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

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 ...
    */
}
思念满溢 2024-09-02 16:42:34

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

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

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

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文