Google Code Prettify

2010年12月18日 星期六

C - 文章排版程式(單字處理)


word.h
#ifndef WORD_H
#define WORD_H
/**********************************************************
* Read_word: Reads the next word from the input and *
* stores it in word. Makes word empty if no *
* word could be read because of end-of-file. *
* Truncates the word if its length exceeds *
* len. *
**********************************************************/
void read_word(char *word, int len);
#endif
view raw word.h hosted with ❤ by GitHub

word.c
#include <stdio.h>
#include <string.h>
#include "word.h"
int read_char(void) //抓取需要的字。
{
int ch = getchar();
if (ch == '\n' || ch == '\t')
return ' ';
return ch;
}
void read_word(char *word, int len) //將文章的字存入word,沒字可讀時便存入\0。
{
int ch, pos = 0;
while ((ch = read_char()) == ' ') //略過第一個字前的空格。
;
while (ch != ' ' && ch != EOF) { //讀入字串
word[pos++] = ch;
ch = read_char();
}
word[pos] = '\0';
if (pos >= len) { //若單字長度超過最大長度,則將超過最大長度的字元輸出至另一個檔。
FILE *out;
out = fopen("lost_words", "a+");
pos = len - 1;
do {
fprintf(out, "%c", word[pos++]);
} while (word[pos] != '\0');
fprintf(out, "\n");
word[len] = '\0';
}
}
view raw word.c hosted with ❤ by GitHub

沒有留言:

張貼留言