c - 浏览文件行 - C

标签 c file io

是否有任何方法可以通过选择上下移动行号而不是按顺序来浏览文件?

到目前为止,我的代码使用 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/

相关文章:

c - K 和 R 练习 1-22

algorithm - 文件、月份、模块和伪代码

java - hadoop No FileSystem for scheme : file

http.Get() 从 url 获取图像并写入 GridFS

java - 在默认文件资源管理器中打开文件并使用 JavaFX 或纯 Java 突出显示它

c - 有没有办法从C文件中调用6502汇编代码?

c - 宏依赖宏

c - 通过它的 child 分析一个过程,然后杀死 child

java - 为 J2ME 应用程序中使用的一组 key 对值编制索引

python - 使用 Python 3 创建具有唯一名称的临时文件?