69,382
社区成员
发帖
与我相关
我的任务
分享
/* addaword.c -- uses fprintf(), fscanf(), and rewind() */
/* 文件测试程序 */
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define CNTL_Z '\032' //DOS文本文件中的文件结尾标记
int main(void)
{
FILE *fp;
char words[MAX];
long first, last;
char c;
if ((fp = fopen("words", "a+")) == NULL) //不能打开文件就返回NULL
{
fprintf(stdout, "Can't open \"words\" file\n");
exit(1);
}
printf("Input words:\n");
while (gets(words) != NULL)
{
fprintf(fp, "%s ", words);
}
puts("File contents:"); //文件内容
rewind(fp); //rewind()命令使程序回到文件开始处,这样
//最后的while循环就可以打印文件的内容
while (fscanf(fp, "%s", words) == 1)
{
puts(words);
}
fseek(fp, 0L, SEEK_END);
last = ftell(fp);
for (first = 0L; first <= last; ++first)
{
fseek(fp, -first, SEEK_END);
c = getc(fp);
if (c!=CNTL_Z && c!='\r')
{
putchar(c);
}
}
putchar('\n');
if (fclose(fp) != 0)
{
fprintf(stderr, "Error closing file\n");
}
return 0;
}