我按照题目要求写了一个,我对题目要求作了一点更改,要是两个文件之一存在输入的字符串,则只打印是否是回文的信息,而不再把字符串写入文件。
你可以参考一下我的代码,有什么错误或者不足请指出
[CODE]/* isPalindrome.c -- 判断一个字符串是否是回文,并作相应文件操作
* Author: Space
* Date: 2007/07/07
* Version: 1.0
*/
#include <stdio.h>
#include <string.h>
#define IS_HUIWEN "yeshuiwen.txt"
#define ISNOT_HUIWEN "nohuiwen.txt"
#define BUFSIZE 1024
#define TRUE 1
#define FALSE 0
int isPalindrome(const char *str);
int main(void)
{
FILE *pf = NULL;
char input[BUFSIZE] = "\0";
char strInFile[BUFSIZE] = "\0";
int found = FALSE;
int inHWFile = FALSE;
int inNotHWFile = FALSE;
printf("Please enter a string:\n");
fgets(input, BUFSIZE, stdin);
if ((pf = fopen(IS_HUIWEN, "r")) == NULL)
{
printf("Open file %s failed!\n", IS_HUIWEN);
exit(-1);
}
while (fgets(strInFile, BUFSIZE, pf) != NULL)
{
if (strcmp(input, strInFile) == 0)
{
found = TRUE;
inHWFile = TRUE;
break;
}
}
fclose(pf);
if (! found)
{
if ((pf = fopen(ISNOT_HUIWEN, "r")) == NULL)
{
printf("Open file %s failed!\n", ISNOT_HUIWEN);
exit(-1);
}
while (fgets(strInFile, BUFSIZE, pf) != NULL)
{
if (strcmp(input, strInFile) == 0)
{
found = TRUE;
inNotHWFile = TRUE;
break;
}
}
fclose(pf);
}
if (found)
{
if (inNotHWFile)
printf("The string you entered is not a palindrome string.\n");
else if (inHWFile)
printf("The string you entered is a palindrome string.\n");
}
else
{
if (isPalindrome(input))
{
printf("The string you entered is a palindrome string.\n");
if ((pf = fopen(IS_HUIWEN, "a")) == NULL)
{
printf("Open file %s failed!\n", IS_HUIWEN);
exit(-1);
}
fputs(input, pf);
fclose(pf);
}
else
{
printf("The string you entered is not a palindrome string.\n");
if ((pf = fopen(ISNOT_HUIWEN, "a")) == NULL)
{
printf("Open file %s failed!\n", ISNOT_HUIWEN);
exit(-1);
}
fputs(input, pf);
fclose(pf);
}
}
return 0;
}
int isPalindrome(const char *str)
{
int i = 0;
int len = strlen(str) - 1;
while (i++ < len / 2 + 1)
{
if (str[i] != str[len - i - 1])
return FALSE;
}
return TRUE;
}
[/CODE]