【说明】
对指定文件中的内容或传入的字符串参数逆序打印并保存到文件中。
【命令行示例】
[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;
}