3

我正在尝试找到一种方法来使用 C(不是 c++ 或 c#,只是 C)选择文本文件的最后一行,如果有人可以帮助我解决这个问题,我很难找到一种方法我将不胜感激,谢谢!(顺便说一句,这是我正在尝试做的一个很好的例子,这与 tail -n 1 在 bash 中所做的类似)

4

5 回答 5

6
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(int argc, char *argv[])
{
    FILE *fd; // File pointer
    char filename[] = "./Makefile"; // file to read
    char buff[1024];

    if ((fd = fopen(filename, "r")) != NULL) // open file
    {
        fseek(fd, 0, SEEK_SET); // make sure start from 0

        while(!feof(fd))
        {
            memset(buff, 0x00, 1024); // clean buffer
            fscanf(fd, "%[^\n]\n", buff); // read file *prefer using fscanf
        }
        printf("Last Line :: %s\n", buff);
    }
}

我正在使用 Linux。CMIIW

于 2012-05-07T10:09:15.140 回答
5

没有直接的方法,但我首选的方法是:

  1. 转到文件末尾
  2. 读取最后 X 个字节
  3. 如果它们包含 '\n' - 你得到了你的行 - 从该偏移量读取到文件末尾
  4. 在它们之前读取 X 个字节
  5. 回到 3 直到找到匹配
  6. 如果到达文件的开头 - 整个文件是最后一行
于 2012-05-07T04:05:59.600 回答
1

E.g.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef max
#define max(a, b) ((a)>(b))? (a) : (b)
#endif

long GetFileSize(FILE *fp){
    long fsize = 0;

    fseek(fp,0,SEEK_END);
    fsize = ftell(fp); 
    fseek(fp,0,SEEK_SET);//reset stream position!!

    return fsize;
}
char *lastline(char *filepath){
    FILE *fp;
    char buff[4096+1];
    int size,i;
    long fsize;
    if(NULL==(fp=fopen(filepath, "r"))){
        perror("file cannot open at lastline");
        return NULL;
    }
    fsize= -1L*GetFileSize(fp);
    if(size=fseek(fp, max(fsize, -4096L), SEEK_END)){
        perror("cannot seek");
        exit(1);
    }
    size=fread(buff, sizeof(char), 4096, fp);
    fclose(fp);
    buff[size] = '\0';
    i=size-1;
    if(buff[i]=='\n'){
        buff[i] = '\0';
    }
    while(i >=0 && buff[i] != '\n')
        --i;
    ++i;
    return strdup(&buff[i]);
}

int main(void){
    char *last;

    last = lastline("data.txt");
    printf("\"%s\"\n", last);
    free(last);
    return 0;
}
于 2012-05-07T09:35:01.330 回答
0

一种简单而低效的方法是将每一行读入缓冲区。
当最后一次读取给你时EOF,你在缓冲区中有最后一行。

Binyamin Sharet 的建议更有效,但实施起来有点困难。

于 2012-05-07T06:20:27.677 回答
0

如果你使用*nix 操作系统,你可以使用命令'last'。有关详细信息,请参见“最后一个”手册页。如果你想将功能集成到另一个程序中,你可以使用'system'调用来执行'last'并得到它的结果。

于 2012-05-07T05:13:29.160 回答