C Primer Plus 第十三章 编程练习9

作者在 2013-05-13 11:06:21 发布以下内容
/*
修改程序清单13.3中的程序.
从1开始,根据加入列表的顺序为每个单词编号,当再次运行程序时
确保新的单词编号接着前面的编号开始. 
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 40

int main(int argc, char *argv[])
{
	FILE *fp;
	char words[MAX];
	unsigned int i = 0;
	char ch;
	
	if((fp = fopen("words", "a+")) == NULL)	/*如果打开文件或创建文件失败,退出程序*/
	{
		fprintf(stderr, "Can't create \"words\" file.\n");
		exit(1);
	}
	else									/*如果打开文件,则每读到一个空格,*/
	{										/*视为增加一个单词数,编号数增加1*/
		while((ch = getc(fp)) != EOF)		/*如果文件为新创建的,编号不会变化*/
			if(ch == ' ')
				i++;						/*保存最大的编号数*/
	}

	puts("Enter words to add to the file: press the Enter");
	puts("key at the beginning of a line to terminate.");
	
	rewind(fp);
	while(gets(words) != NULL && words[0] != '\0')
	{
		fprintf(fp, "%d.%s ", ++i, words);		/*将编号与单词写入文件 单词以空格结尾*/
	}
	
	puts("File contents: ");
	rewind(fp);
	
	while(fscanf(fp, "%s", words) == 1)
		puts(words);
		
	close(fp);
	return 0;
}
文章评论,共0条
游客请输入验证码
浏览39539次