如何将文本文件最后一行的内容复制到第一行?C编程



我正在编写一个程序,将文本文件"input.txt"复制到"output.txt",但我不需要将第一行复制到最后一行,而是需要将最后一行反向复制到"output.txt"文件的第一行。有人能给点建议吗?谢谢!

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    char filename[]={"input.txt"};
    char filename2[]={"output.txt"};
    char a;
    FILE *inptr, *outptr;
    inptr = fopen(filename, "r");
    if(inptr == NULL)
    {
        printf("The file could not be opened!n");
        system("pause");
        return 1;
    }
    outptr = fopen(filename2, "w");
    if(outptr == NULL)
    {
        printf("The file could not be opened!n");
        printf("Creating a new file......n");
        system("pause");
        return 1;
    }
    while((fscanf(inptr, "%c", &a)) != EOF)
    {
        fprintf(outptr, "%c", a);
        puts("A character was copied!nn");
    }
    fclose(inptr);
    fclose(outptr);
    system("pause");
    return 0;
}

例如,假设文本文件中有3行:

嗨再见你好

所以我需要将上下文复制到另一个文件,但它从开始

你好再见嗨

谢谢!

在如下方法中,在有足够内存的情况下,可以读取并处理内存中的文件。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
    char *str;
    struct node *next;
} Node;
Node *pushNode(Node *current, char *str){
    Node *node = malloc(sizeof(Node));
    if(node){
        node->str = strdup(str);
        node->next = current;
    }
    return node;
}
char *popNode(Node **current){
    if(*current){
        Node wk = **current;
        free(*current);
        *current = wk.next;
        return wk.str;
    }
    return NULL;
}
#define MAXOFLINESIZE 1024
int main(){
    char *str, buff[MAXOFLINESIZE];//max size include ''
    Node *current = NULL;
    FILE *inFile, *outFile;
    inFile = stdin;//Mock
    outFile = stdout;
    while(NULL!=fgets(buff, sizeof(buff), inFile)){
        current=pushNode(current, buff);//need check return of pushNode
    }
    while(NULL!=(str=popNode(&current))){
        fprintf(outFile, "%s", str);
    }
    return 0;
}

您可以正向读取输入文件中的行。你能想到任何可以存储行的数据结构吗?数据结构应该可以帮助您按相反的顺序输出行。

我不会一个字符一个字符地阅读它。C中有逐行读取的函数,例如fgets()。因此,对于每一行,您可以分配一个缓冲区,将该行读取到缓冲区中,并将指向缓冲区的指针存储在数组中。一旦你完成。从数组的末尾开始,输出存储的字符串。令人痛苦的是,C没有动态数组,所以你必须模仿它(malloc,free),除非你事先知道行的最大长度和最大数量。

或者,应该有一种方法可以做到这一点,而无需将整个文件加载到内存中(在源文件中标记换行位置,然后按相反的顺序查找)。

最新更新