读取文件以行为单位逆序输出到另一文件

来源:互联网 发布:淘宝加钱换购怎么设置 编辑:程序博客网 时间:2024/05/16 10:06

首先要声明的一点时,一篇文档只是提供了一种思路或解决办法,不一定是最有效或最通用的,这里仅仅是期望会对他人有些借鉴的意义。

先来说明问题:从A文件读取文本内容,要求以逆序的方式写入到B文件中,逆序以行为单位。如

A.txt文件的内容为:

122344ff

最后输出到B.txt中的内容为:

ff442312

整个问题说起来实在是不难,如果是C++或者Java,使用Vector非常容易实现相关功能。难的是如何占用最少的资源,不把所有文件内容缓存能不能完成要求?

其实这个问题要考虑两个方面:1、文件大小;2、系统资源是否充足

如果系统文件不大,那么完全可以缓存整个文件内容;如果系统文件较大或者系统资源不宽裕的情况,那就要考虑采用别的方法了。

如果不缓冲文本内容,可以考虑这种思路:首先seek到A的文件末尾,然后向前搜索回车符"\n",搜索到后从"\n"的下一位置读取一行文本,这里可能需要保存当前读取行内容的位置,一直向前搜索"\n"读取一行,直到当前位置到文件的起始位置0.

如果缓冲文本,相对来说较为简单,C语言中可以使用链表完成文本内容的缓存,下面为一段示例代码可以作为参考:

#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAXSIZE 1024struct node{    char *line;    struct node *next;};int main(int argc, char **argv){    struct node *head = (struct node*)malloc(sizeof(struct node));    FILE *in, *out;    char buf[MAXSIZE];    if(argc < 2){        printf("Please append the filename\n");        return 0;    }        if(NULL == (in = fopen(argv[1], "r"))){        printf("Error while open %s\n", argv[1]);        return -1;    }    if(NULL == (out = fopen("result.txt", "w"))){        printf("Error while open result.txt\n");        close(in);        return -1;    }    head->next = NULL;    while(NULL != fgets(buf, MAXSIZE, in)){        struct node *pnode = (struct node*)malloc(sizeof(struct node));        pnode->line = (char*)malloc(strlen(buf));        pnode->next = NULL;        sprintf(pnode->line, "%s", buf);        if(NULL != head->next){            pnode->next = head->next;            head->next = pnode;        }else{            head->next = pnode;        }    }    while(NULL != head->next){        struct node *pnode = head->next;        fputs(pnode->line, out);        head->next = pnode->next;        free(pnode->line);        free(pnode);    }                                                                     free(head);    fclose(out);    fclose(in);    return 0;}   




 

 

原创粉丝点击