I am also learning C, and I am not a professional. The following is one of the homework for last week. It may help a bit on how pointer works.
This program check a list of word from a file for palindromes (正讀反讀都一樣的詞).
Pointers are very useful when pass data in between functions.
Also give me some comment please.
- #include <stdio.h>
- int readFile(char *, char **);
- void palindromeCheck(char *);
- int main (void)
- {
- char *palindromeList, filename[255] = {'\0'};
- /* ask user for the filename */
- printf("\nPlease enter the filename of your Palindrome list.\n"
- ": ");
- scanf("%s", filename);
- /* read the word list into memory */
- if (readFile(filename, &palindromeList))
- exit(1);
- putc('\n', stdout);
- /* chck each word for palindrome */
- palindromeCheck(palindromeList);
-
- return 0;
- }
- void palindromeCheck(char *buffer)
- {
- int palindrome;
- char *firstChr, *lastChr, *endLine;
- firstChr = endLine = buffer;
- /* loop until end of file */
- while (*firstChr != EOF)
- {
- palindrome = 1;
- /* find the last character */
- while (*endLine != '\n')
- putc(*(endLine++), stdout);
- lastChr = endLine - 1;
- /* palindrome compair */
- while ( (firstChr != lastChr) && ((firstChr + 1) != lastChr) )
- if (*(firstChr++) != *(lastChr--))
- palindrome = 0;
- firstChr = ++endLine;
- /* display result */
- printf(" %s a palindrome\n", (palindrome)? "is":"is not");
- }
- }
- int readFile(char *filename, char **buffer)
- {
- unsigned int count = 0;
- FILE *fptr;
-
- if ( (fptr = fopen(filename, "r")) == NULL )
- {
- fprintf(stderr, "Error Openning Source Code File %s!\n", filename);
- return 1;
- }
-
- /* get the size of the file for memory allocation.
- * read the file onec and count the character make
- * the code protable.*/
- while (getc(fptr) != EOF)
- count++;
- rewind(fptr);
- /* allocate memory */
- *buffer = malloc(count * sizeof(char));
- /* read in the word list and echo them to stdout */
- puts("\nReading Palindrome List From File:");
- count = 0;
- while ( (*(*buffer + count) = getc(fptr)) != EOF)
- putc(*(*buffer + count++), stdout);
-
- fclose(fptr);
- return 0;
- }
复制代码
Data File "test.dat"
- anna
- pip
- +-*-+
- world
- sky
- same
- ga1ag
复制代码
Run Log:
Please enter the filename of your Palindrome list.
: test.dat
Reading Palindrome List From File:
anna
pip
+-*-+
world
sky
same
ga1ag
anna is a palindrome
pip is a palindrome
+-*-+ is a palindrome
world is not a palindrome
sky is not a palindrome
same is not a palindrome
ga1ag is a palindrome |