《C语言及程序设计》程序阅读——文件操作
作者:互联网
返回:贺老师课程教学链接
1、阅读下面的程序,写出输出结果,并上机运行程序进行对照
#include "stdio.h"
int main()
{
FILE *outfile,*infile;
outfile=fopen("data.dat","w");
fprintf(outfile, "1111111111\n");
fprintf(outfile, "aaaaaaaaaa\n");
fprintf(outfile,"AAAAAAAAAA\n");
fprintf(outfile,"**********\n");
fclose(outfile);
infile=fopen("data.dat","r");
char line[80];
int i=0;
while(!feof(infile))
{
i++;
fgets(line,sizeof(line), infile);
printf("%d: %s", i, line);
}
fclose(infile);
return 0;
}
2、区分ASCII文件和二进制文件:阅读并运行下面的两个程序,分别用记事本和二进制文件阅读器(请自行下载Binary Viewer等程序,或者用DOS中的Debug程序,并百度其用法)。查看其内容,并理解文件存储的原理。
(1)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *outfile;
int a;
outfile=fopen("f1.dat","w");
if(!outfile)
{
printf("open error!\n");
exit(1);
}
scanf("%d", &a);
fprintf(outfile, "%d", a);
fclose(outfile);
return 0;
}
(2)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *outfile;
int a;
outfile=fopen("f2.dat","wb");
if(!outfile)
{
printf("open error!\n");
exit(1);
}
scanf("%d", &a);
fwrite(&a, sizeof(int), 1, outfile);
fclose(outfile);
return 0;
}
3、阅读下面的程序,指出其功能,体会fseek()等与文件指针相关的函数的功能及其用法
(1)请说出程序的输出
#include <stdio.h>
#include <stdlib.h>
char *filename = "a.txt";
int main()
{
FILE *file;
long l,m;
file=fopen(filename,"rb");
if(!file)
{
printf("open error!\n");
exit(1);
}
l = ftell(file); //ftell函数返回文件位置指针相对于文件首的偏移量
fseek(file, 0, SEEK_END);
m = ftell(file);
fclose(file);
printf("size of %s is %ld bytes.\n", filename, (m-l));
return 0;
}
(2)请说出运行程序后test.txt中的内容
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *outfile;
long pos;
outfile=fopen("test.txt","w");
if(!outfile)
{
printf("open error!\n");
exit(1);
}
fwrite ("This is an apple",16, 1, outfile);
pos=ftell(outfile);
fseek(outfile, pos-7, SEEK_SET);
fwrite (" sam", 4, 1, outfile);
fclose(outfile);
return 0;
}
标签:int,fclose,程序,C语言,outfile,file,printf,程序设计,include 来源: https://blog.51cto.com/sxhelijian/2814821