C语言 逆序显示文本内容并保存

42 篇文章 2 订阅
21 篇文章 2 订阅

【说明】

    对指定文件中的内容或传入的字符串参数逆序打印并保存到文件中。


【命令行示例】

    [root@localhost]$ ./reverseStr test.txt


    这条命令的含义是读取 ./test.txt 文件中的内容,将文件内容顺序反向存储到 outPut.txt 文件中。


    [root@localhost]$ ./reverseStr "Hello world"


    这条命令的含义是将 "Hello world" 逆序打印到控制台,并存储到文件 outPut.txt 文件中。


【源码】

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(char argc, char **argv)
{
    FILE *pFileRead = NULL;
    char *pstrTarget = NULL;
    char cRead;
    unsigned long ulCountWord = 0;
    char *pstrContent = NULL;
    char *pstrReverse = NULL;
    FILE *pFileOutput = NULL;
    
    if(argc == 2){
        pstrTarget = argv[1];
        if(strstr(pstrTarget, ".txt")){     // 传入参数是文件名
            if(NULL == (pFileRead = fopen(pstrTarget, "r"))){
                printf("open file %s error!\n", pstrTarget);
            }else{
                while(EOF != fscanf(pFileRead, "%c", &cRead)){
                    ++ulCountWord;
                }
                printf("%ld bytes been read.\n", ulCountWord);
                pstrContent = (char *)malloc((size_t)ulCountWord);
                fseek(pFileRead, 0, SEEK_SET);
                printf("%d items been read.\n", fread(pstrContent, sizeof(char), (size_t)ulCountWord, pFileRead));
                pstrReverse = pstrContent;
                printf("content: %s\n", pstrReverse);
                pstrReverse += ulCountWord - 1;
                if(NULL == (pFileOutput = fopen("outPut.txt", "w"))){
                    printf("open file reverseOut.txt error!\n");
                }else{
                    for( ;ulCountWord > 0; ulCountWord--){
                        fprintf(pFileOutput, "%c", *pstrReverse);
                        --pstrReverse;
                    }
                    fprintf(pFileOutput, "%c", *pstrReverse);
                    fclose(pFileOutput);
                }
                free(pstrContent);
                fclose(pFileRead);
            }
        }else{      // 传入参数是字符串内容
            ulCountWord = (unsigned long)strlen(pstrTarget);
            pstrReverse = pstrTarget;
            printf("content: %s\n", pstrReverse);
            pstrReverse += ulCountWord;
            for( ; ulCountWord > 0; ulCountWord--){
                printf("%c", *pstrReverse);
                --pstrReverse;
            }
            printf("%c\n", *pstrReverse);
        }
    }else{
        printf("invalid argument, which should be a filename or a string.\n");
    }
    return 0;
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值