📜  C程序反转文件的内容并打印

📅  最后修改于: 2021-05-17 20:23:14             🧑  作者: Mango

给定目录中的文本文件,任务是向后打印文件内容,即,最后一行应首先打印,第二行最后一行应打印第二,依此类推。

例子:

方法:

  1. 将文本的先前长度初始化为0。
  2. 找到当前行的长度并将其添加到先前的长度。这给出了新行的下一个起始索引。
  3. 重复上述步骤,直到文件结尾。
  4. 在给定文件中初始化给定消息长度的数组。
  5. 现在倒退文件指针,然后将文本的最后一个指针放在arr [K – 1]中,其中K是使用fseek()的数组的长度。
  6. 打印最后一行的长度,并将K减1,以打印文件的下一个最后一行。
  7. 重复上述步骤,直到K等于0。

下面是上述方法的实现:

// C program for the above approach
#include 
#include 
#define MAX 100
  
// Function to reverse the file content
void reverseContent(char* x)
{
  
    // Opening the path entered by user
    FILE* fp = fopen(x, "a+");
  
    // If file is not found then return
    if (fp == NULL) {
        printf("Unable to open file\n");
        return;
    }
  
    // To store the content
    char buf[100];
    int a[MAX], s = 0, c = 0, l;
  
    // Explicitly inserting a newline
    // at the end, so that o/p doesn't
    // get effected.
    fprintf(fp, " \n");
    rewind(fp);
  
    // Adding current length so far +
    // previous length of a line in
    // array such that we have starting
    // indices of upcoming lines
    while (!feof(fp)) {
        fgets(buf, sizeof(buf), fp);
        l = strlen(buf);
        a = s += l;
    }
  
    // Move the pointer back to 0th index
    rewind(fp);
    c -= 1;
  
    // Print the contents
    while (c >= 0) {
        fseek(fp, a, 0);
        fgets(buf, sizeof(buf), fp);
        printf("%s", buf);
        c--;
    }
  
    return ;
}
  
// Driver Code
int main()
{
    // File name in the directory
    char x[] = "file1.txt";
  
    // Function Call to reverse the
    // File Content
    reverseContent(x);
    return 0;
}

输入文件:

输出文件:

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。