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

时间:2013-12-01 22:59:27

标签: c copy filestream

我正在编写一个程序将文本文件“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!\n\n");
    }

    fclose(inptr);
    fclose(outptr);

    system("pause");
    return 0;
}

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

您好 再见 你好

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

您好 再见 喜

谢谢!

3 个答案:

答案 0 :(得分:1)

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

#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 '\0'
    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;
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我不会用char读它char。 C中有逐行读取函数,例如fgets()。 因此,对于每一行,您可以分配一个缓冲区,将该行读入缓冲区,并将指针存储在数组中的缓冲区中。一旦你完成了。你从数组的末尾开始并输出存储的字符串。 关于这一点的痛苦部分是C没有动态数组,因此您必须模拟( malloc,free ),除非您事先知道线的最大长度及其最大数量。

或者,应该有一种方法可以在不将整个文件加载到内存中的情况下执行此操作(在源文件中标记换行位置,然后以相反的顺序搜索它们)。