当前位置:网站首页>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)结果有什么不同。
四、实验注意事项
注意文件打开的不同方式。
边栏推荐
猜你喜欢
redis持久化方式
响应式织梦模板餐饮酒店类网站
用栈实现队列
The salary of soft testers at each stage, come to Kangkang, how much can you get?
栈的压入、弹出序列
射频芯片(RFIC)的协议之5G及其调制
In V8 how arrays (with source code, picture and text easier to understand)
Fluorescein-PEG-CLS,胆固醇-聚乙二醇-荧光素科研试剂
complete binary tree problem
Redis persistence method
随机推荐
CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应
Storage engine written by golang, based on b+ tree, mmap
全球首款量产,获定点最多!这家AVP Tier1如何实现领跑?
How many way of calling a function?
栈的压入、弹出序列
代码重构:面向单元测试
Three.js入门详解
国内首发可视化智能调优平台,小龙带你玩转KeenTune UI
BPF 可移植性和 CO-RE(一次编译,到处运行)
[2022安恒夏令营] 5个小题
HNUCM 您好中国
V8中的快慢数组(附源码、图文更易理解)
简单了解下 TCP,学习握手和挥手以及各种状态到底是怎么样的
Shell 用法梳理总结
【LeetCode】最长公共子序列(动态规划)
【OpenCV图像处理】 图像拼接技术
七夕活动浪漫上线,别让网络拖慢和小姐姐的开黑时间
A simple understanding of TCP, learn how to shake hands, wave hands and various states
Why Flutter Flutter of tutorials is the best choice for business?
rsync 基础用法