有没有办法浏览文件,可以选择上下移动行号而不是顺序?
截至目前,我的代码使用fgets来获取文件中的最后一行ascii字符,但通过我的研究,我还没有找到一种更智能的方法来遍历文件。
例如:
file.txt contains:
"hello\n"
"what's up?\n"
"bye"
我需要能够返回" bye"首先,然后使用按键,打印"什么是"然后再回到" bye"通过另一个按键。
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *infile;
char *infile_contents;
unsigned int infile_size;
// to read all of the file
infile = fopen("file.txt", "rb");
fseek(infile, 0, SEEK_END);
infile_size = ftell(infile);
fseek(infile, 0,SEEK_SET);
infile_contents = malloc(infile_size+1);
fread(infile_contents, infile_size, 1, infile);
fclose(infile);
infile_contents[infile_size]=0;
// to store the beginning of lines and replace '\n' with '\0'
size_t num_lines = 1, current_line = 1, length;
char **lines = malloc(sizeof(char*)), **lines1, *tmp;
lines[0] = infile_contents;
while(tmp = strchr(infile_contents, '\n'))
{
// to resize lines if it is not big enough
if(num_lines == current_line)
{
lines1 = lines;
lines = malloc((num_lines<<1)*sizeof(char*));
memcpy(lines, lines1, num_lines*sizeof(char*));
memset(lines+num_lines, 0, num_lines*sizeof(char*));
num_lines <<= 1;
free(lines1);
}
*tmp=0;
infile_contents = tmp+1;
lines[current_line++] = infile_contents;
}
// to print the lines
num_lines = current_line-1;
current_line = num_lines;
// to skip the last line if it is empty
if(!lines[current_line][0])
{
num_lines--;
current_line = num_lines;
}
while(1)
{
printf("%s",lines[current_line]);
if(getchar())// change to the condition for going down
{
if(current_line)
current_line--;
else
current_line=num_lines;
}
else
{
if(current_line==num_lines)
current_line=0;
else
current_line++;
}
}
}