簡體   English   中英

如何將內容從文本文件的最后一行復制到第一行? C程序設計

[英]How to copy the contents from the last line of a text file to the first line? C programming

我正在編寫一個程序,將文本文件“ input.txt”復制到“ output.txt”,但是與其將第一行復制到最后一行,我需要將最后一行反向復制到“輸出”。 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行:

嗨再見

所以我需要將上下文復制到另一個文件,但是它從以下位置開始:

你好再見

謝謝!

在有足夠內存的情況下,可以通過以下方法讀取和處理內存中的文件。

#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;
}

您可以從輸入文件中向前讀取行。 您能想到可以存儲行的任何數據結構嗎? 數據結構應幫助您以相反的順序輸出行。

我不會一個字一個字符地讀它。 C中有逐行讀取功能,例如fgets()。 因此,對於每一行,您可以分配一個緩沖區,將該行讀入緩沖區,然后將指向緩沖區的指針存儲在數組中。 完成后。 您從數組的末尾開始並輸出存儲的字符串。 痛苦的部分是C沒有動態數組,因此您必須模擬( malloc,free ),除非您事先知道行的最大長度及其最大數量。

或者,應該有一種方法可以做到這一點,而無需將整個文件加載到內存中(在源文件中標記換行符,然后以相反的順序查找它們)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM