【C语言】读取指定行范围内容之终止行和文本文件总行数之间的关系问题

版权声明:可以转载奥 https://blog.csdn.net/Jiajikang_jjk/article/details/86690600

【C语言】读取指定行范围内容之终止行和文本文件总行数之间的关系问题

一、问题描述

         在读取指定行范围内容的时候,比如读取一个文本文件的10-20行的内容,原则上就打印:10,11,12,,,20行的内容,But,要是文本文件中的内容只有15行内容该当如何?
         按照博主的想法:终止行>文本文件总行数,那就从输入的起始行开始读取到文本文件总行数就ok。
         注: 这里只讨论以上陈述问题,且不考虑起始行和终止行的关系,起始行和文本文件总行数的关系等等。

一、流程图

在这里插入图片描述

二、代码

/*

程序功能: 读取指定行范围
主要目的: 解决终止行和文本文件总行数之间的关系
        


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

#define MAX 1024
int displayLine(FILE *file, int isDisplay);

int main()
{
    int index = 1;
    int start = 2; // 起始行
    int end = 20;  // 终止行

    FILE *file = fopen("./wenben/wenben.txt", "r");

    while (1)
    {
        if (index >= start && index <= end)
        {
            int isTextEnd = displayLine(file, 1);
            index++;
            if (isTextEnd)
            {
                break;
            }
            printf("\n");
        }
        else if (index > end)
        {
            break;
        }
        else
        {
            int isTextEnd = displayLine(file, 0);
            if (isTextEnd)
            {
                break;
            }
            index++;
        }
    }
    return 0;
}


// 创建子函数
int displayLine(FILE *file, int isDisplay)
{
    char read;
    read = fgetc(file); // 按照字符读取

    int index = 0;
    char chars[MAX];
    memset(chars, 0, MAX);//  void *memset(void *s,int c,size_t n):将已开辟内存空间 s 的首 n 个字节的值设为值 c。
    while (read != '\n') 
    {
        if (read == EOF) 
        {
            if (isDisplay)
            {
                for (int i = 0; i < index; i++)
                {
                    printf("%c", chars[i]);
                }
            }
            return 1;
        }
        chars[index] = read;
        index++;
        read = fgetc(file);
    }


    if (isDisplay)
    {
        for (int i = 0; i < index; i++)
        {
            printf("%c", chars[i]);
        }
    }
    return 0;
}

三、原文本文件内容

在这里插入图片描述

四、测试结果

         为了测试简单,实现速度快,代码中将写要测试的行范围写死了(起始行:2,终止行:20)。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Jiajikang_jjk/article/details/86690600