C语言文件写操作会将文件指针移动到文件尾,故不能接着读操作不会从文件头开始

本程序实现单词长度计数,打印相应直方图,以及记录超过规定数量的单词


对文件进行写操作以后文件指针指向文件尾,故直接读操作不会读取到相应内容,即在代码中去除

fseek(fp, 0, 0);

文件读操作就读不到相应的内容。

#include 
#define N 11
#define IN 1  //in a word
#define OUT 0  //out a word
#define MAXLENOFWORD 10

//the file must be readable
void display_diagram(FILE *fp) {
	int a[N] = {0};
	int c, state = OUT, nc = 0;
	int ovflow = 0;
	int i, j;
	
	while ((c = getc(fp)) != EOF) {
		if (c == ' ' || c == '\t' || c == '\n') {
			if (state == IN) {
				if (nc > MAXLENOFWORD) {
					++ovflow;
				} else {
					++a[nc];
				}
				state = OUT;
			}
		}	
		else if (state == OUT) {
			state = IN;
			nc = 1;
		}		
		else  {
			++nc;
		}
	}
	
	for (i = 1; i < N; ++i) {
		printf("%3d : ", i);
		for (j = 1; j <= a[i]; ++j) {
			putchar('*');
		}
		printf("\n");
	}
	printf("There is %d word over %d\n", ovflow, MAXLENOFWORD);	
}

int main() {
	FILE *fp; 
	int i, j, k;
	
	fp = fopen("1-13theword", "w+");
	if (fp == NULL) {
		printf("file cannot be opened!\n");
		return 0;
	}
	 
	for (i = 1; i < N; ++i) {
		for (j = 1; j <= i; ++j) {
			for (k = 1; k <= i; ++k) {
				putc('*', fp);
			}
			putc(' ', fp);		
		}
		putc('\n', fp);
	}
	//after this the fp is pointer to the end of file
	fseek(fp, 0, 0);
	display_diagram(fp);
	
	fclose(fp);
	return 0;
}

运行结果


C语言文件写操作会将文件指针移动到文件尾,故不能接着读操作不会从文件头开始_第1张图片 

你可能感兴趣的:(C语言文件写操作会将文件指针移动到文件尾,故不能接着读操作不会从文件头开始)