当前位置:网站首页>C语言实验十五 文件
C语言实验十五 文件
2022-08-03 23:37:00 【Meteor.792】
一、实验目的
(一)掌握文件以及缓冲文件系统、文件指针的概念;
(二)学会使用文件打开、关闭、读、写等文件操作函数;
(三)学会用缓冲文件系统对文件进行简单的操作。
二、预习要求
文件类型指针
文件的打开与关闭 文件的读写操作函数
三、实验内容
将一个磁盘文件中的信息复制到另一个磁盘文件中。
#include <stdio.h>
#include <stdlib.h>
void main( )
{
FILE*in,*out ; // 定义文件指针
char ch,infile[1 0],outfile[1 0];
printf("Enter the infile name:\n");
scanf("%s",infile);
printf("Enter the outfile name:\n");
scanf("%s",outfile);
if((in=fopen(infile," r"))==NULL)
{ // 判断文件是否正确读操作
printf("cannot open infile\n"); exit(0);
}
if((out=fopen(outfile,"w"))==NULL)
{ // 判断文件是否正确写操作
printf("cannot open outfile\n"); exit(0);
}
//判文件是否结束,如果不结束,则读文件in 的内容写入到文件out 之中
while(!feof(in)) fputc(fgetc(in),out);
fclose(in); //关闭文件
fclose(out);
}运行情况如下:
Enter the infile name:
file1.c(输入原有磁盘文件名)
Enter the outfile name:
file2.c(输入新复制的磁盘文件名)程序运行结果是将 fule1. c 文件中的内容复制到 fule2. c 中去。可以用下面命令验证:
c:\>type file1.c
computer and c (file1.c中的信息)
c:\>type file2.c
computer and c (file2.c 中的信息)以上程序是按文本文件方式处理的。也可以用此程序来复制一个二进制文件,只需 将两个 fopen 函数中的“r” 和 “w”分别改为“rb” 和 “wb” 即可。
分析以上各程序的算法(用框图表示),解释产生该结果现象的相关知识点及实现语句。
阅读以下程序,回答后面的问题。
#include <stdio.h>
void main(void)
{
short a=0x253f,b=0x7b7d; char ch;
FILE *fp1,*fp2;
fp1=fopen("c:\\abc1.bin","wb+");
fp2=fopen("c:\\abc2.txt","w+");
fwrite(&a,sizeof(short), 1 ,fp1);
fwrite(&b,sizeof(short), 1 ,fp 1);
fprintf(fp2,"%hx %hx",a,b); rewind(fp 1); rewind(fp2);
while((ch = fgetc(fp1)) != EOF) putchar(ch);
putchar('\n');
while((ch = fgetc(fp2)) != EOF) putchar(ch);
putchar('\n');
fclose(fp 1);
fclose(fp2);
}(1)请思考程序的输出结果, 然后通过上机运行来加以验证。
(2)将两处 sizeof(short)均改为 sizeof(char)结果有什么不同,为什么?
(3)将 fprintf(fp2,"%hx %hx",a,b) 改为 fprintf(fp2,"%d %d",a,b)结果有什么不同。
四、实验注意事项
注意文件打开的不同方式。
边栏推荐
猜你喜欢

(PC+WAP)织梦模板螺钉手柄类网站

Fluorescein-PEG-CLS,胆固醇-聚乙二醇-荧光素科研试剂

Pytest学习-skip/skipif

Creo 9.0在草图环境中创建坐标系

ML's yellowbrick: A case of interpretability (threshold map) for LoR logistic regression model using yellowbrick based on whether Titanic was rescued or not based on the two-class prediction dataset

射频芯片(RFIC)的协议之5G及其调制

一文搞定 SQL Server 执行计划

Click the icon in Canvas App to generate PDF and save it to Dataverse

Fluorescein-PEG-CLS, cholesterol-polyethylene glycol-fluorescein scientific research reagent

Redis persistence method
随机推荐
Scala basics [regular expressions, framework development principles]
七夕活动浪漫上线,别让网络拖慢和小姐姐的开黑时间
Three.js入门详解
JS get parameter value of URL hyperlink
Walk the Maze BFS
Go编译原理系列7(Go源码调试)
Pytest learn-setup/teardown
【OpenCV图像处理】 图像拼接技术
SPOJ 2774 Longest Common Substring(两串求公共子串 SAM)
响应式织梦模板餐饮酒店类网站
Use tf.image.resize() and tf.image.resize_with_pad() to resize images
雅思大作文写作模版
Create function report error, prompting DECLARE definition syntax problem
走迷宫 BFS
简单了解下 TCP,学习握手和挥手以及各种状态到底是怎么样的
IELTS essay writing template
rosbridge-WSL2 && carla-win11
【职场杂谈】售前与销售工作配合探讨
密码学基础以及完整加密通讯过程解析
Creo 9.0创建几何点