给定目录中的文本文件,任务是向后打印文件内容,即最后一行应该首先打印,最后第二行应该第二打印,依此类推。
例子:
Input:
file1.txt has:
Welcome
to
GeeksforGeeks
Output:
GeeksforGeeks
to
Welcome
GeeksforGeeks
Input:
file1.txt has:
This is line one
This is line two
This is line three
This is line four
This is line five
Output:
This is line five
This is line four
This is line three
This is line two
This is line one
方法:
- 将文本的先前长度初始化为 0。
- 找到当前行的长度并将其添加到先前的长度。这给出了新行的下一个起始索引。
- 重复以上步骤直到文件结束。
- 初始化给定文件中给定消息的长度数组。
- 现在倒回文件指针并将文本的最后一个指针放置到arr[K – 1] ,其中K是使用 fseek() 的数组长度。
- 打印最后一行的长度并将K减1以打印文件的下一行。
- 重复以上步骤,直到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;
}
输入文件:
输出文件:
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。