重写C语言中的fgets函数,从文件底部开始读取
时间: 2024-05-02 14:22:50 浏览: 85
c语言fgets fputs 读写文件
4星 · 用户满意度95%
抱歉,我作为一名AI语言模型,无法进行实际的编程操作。不过,关于你提到的问题,你可能需要使用 fseek 函数将文件指针定位至文件末尾,再逐行读取文件内容,这样就可以实现从文件底部开始读取的效果。具体代码实现可以参考下面这段示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
char* read_lines_from_end(const char* file_path, int count)
{
char* buffer = (char *) malloc(BUFFER_SIZE * count * sizeof(char));
FILE* fp = fopen(file_path, "r");
if (fp == NULL)
{
printf("Failed to open file!\n");
return NULL;
}
// 移动文件指针到文件末尾
if (fseek(fp, 0L, SEEK_END) != 0)
{
printf("Failed to seek to end of file!\n");
fclose(fp);
free(buffer);
return NULL;
}
// 获取当前文件指针位置
long file_offset = ftell(fp);
printf("File size is %ld bytes.\n", file_offset);
// 逐行读取文件内容
int lines_read = 0;
char line_buffer[BUFFER_SIZE];
while (lines_read < count)
{
// 根据文件指针位置计算行的偏移量
long line_offset = 0;
int last_char = '\n';
while (file_offset > 0 && last_char != '\n')
{
if (fseek(fp, --file_offset, SEEK_SET) != 0)
{
printf("Failed to seek to offset %ld!\n", file_offset);
fclose(fp);
free(buffer);
return NULL;
}
last_char = fgetc(fp);
line_offset++;
}
if (file_offset == 0)
{
// 读到文件开头后退出循环
break;
}
// 读取一行文件内容
if (fgets(line_buffer, BUFFER_SIZE, fp) == NULL)
{
printf("Failed to read line at offset %ld!\n", file_offset);
fclose(fp);
free(buffer);
return NULL;
}
// 将读取到的文件内容复制到缓冲区中
int line_length = strlen(line_buffer);
if (line_length > 0 && line_buffer[line_length - 1] == '\n')
{
line_buffer[line_length - 1] = '\0';
}
strcat(buffer, line_buffer);
strcat(buffer, "\n");
lines_read++;
}
// 关闭文件并返回缓冲区指针
fclose(fp);
return buffer;
}
int main(int argc, char* argv[])
{
if (argc < 3)
{
printf("Usage: read_lines_from_end <file_path> <count>\n");
return -1;
}
const char* file_path = argv[1];
int count = atoi(argv[2]);
char* lines = read_lines_from_end(file_path, count);
if (lines == NULL)
{
printf("Failed to read lines from file.\n");
return -1;
}
printf("Last %d lines from file:\n", count);
printf("%s", lines);
free(lines);
return 0;
}
```
阅读全文