是否有任何方法可以通过选择上下移动行号而不是按顺序来浏览文件?
到目前为止,我的代码使用 fgets 来获取文件中最后一行 ascii 字符,但通过我的研究,我还没有找到更智能的方式来迭代文件。
例如:
file.txt contains:
"hello\n"
"what's up?\n"
"bye"
我需要能够首先返回“bye”,然后使用按键,打印“what's up\n”,然后通过另一个按键返回“bye”。
最佳答案
#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++;
}
}
}
关于c - 浏览文件行 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36347504/