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

作者在 2013-05-13 11:50:48 发布以下内容
/*
编写一个程序,打开一个文本文件,文件名通过交互方式获得.
建立一个循环,请求用户输入一个文件位置.
然后程序打印文件中从该位置开始到下一换行符之间的部分.
用户通过输入非数字字符来终止输入循环. 
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 40

int main(int argc, char *argv[])
{
	char file[SIZE];
	FILE * fp;
	long i, bytes;
	char ch;
	
	printf("Enter file name: ");
	gets(file);
	
	if((fp = fopen(file, "r")) == NULL)
	{
		fprintf(stderr, "Can't open file :\"%s\".", file);
		exit(1);
	}
	fseek(fp, 0L, SEEK_END);
	bytes = ftell(fp);			/*获得文件字节数*/
	
	printf("Enter number (q to quit): ");
	while(scanf("%ld", &i) == 1)
	{
		if(i >= bytes)
		{
			fprintf(stderr, "More than the file size.\n");
			printf("Retry (q to quit): ");
			continue;
		}
		
		fseek(fp, i, SEEK_SET);		/*定位到输入的数字位置*/
		while((ch = getc(fp)) != '\n' && ch != '\r' && ch != EOF)
			putc(ch, stdout);
		
		printf("\n\nNext number (q to quit): ");
	}
	
	close(fp);
	printf("\n\nDone.\n");
	return 0;
}
文章评论,共0条
游客请输入验证码
浏览39553次